NSString 到 NSDate,格式为 mm/dd/yyyy hh:mm:ss

发布于 2024-11-28 06:58:09 字数 294 浏览 1 评论 0原文

我收到的日期字符串是这种格式的 8/5/2011 1:38:13 PM。如何将其转换为 NSDate

我尝试过:

[dateFormatter setDateFormat:@"mm/dd/yyyy 'T' hh:mm:ss a"];
NSString *currentDate = [dateFormatter stringFromDate:currentDateString];

它返回nil。有什么想法吗?

My date string that I am getting is 8/5/2011 1:38:13 PM of this format. How do I convert it to NSDate?

I tried:

[dateFormatter setDateFormat:@"mm/dd/yyyy 'T' hh:mm:ss a"];
NSString *currentDate = [dateFormatter stringFromDate:currentDateString];

It returns nil. Any thoughts?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

审判长 2024-12-05 06:58:10

它返回 nil 的原因是因为您调用了错误的方法,日期字符串中没有 T (单引号 ' 中的字符是文字​​),并且下午不是“下午”。没有破坏它但不完全正确的是你试图将月份解析为分钟,并且你的日期字符串可以至少有 1 位数的月份、日期和小时,所以你不应该使用 2 个说明符来填充它们如果您要根据日期创建一个字符串。试试这个:

NSString *currentDateString = @"8/5/2011 1:38:13 PM";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//Set the AM and PM symbols
[dateFormatter setAMSymbol:@"AM"];
[dateFormatter setPMSymbol:@"PM"];
//Specify only 1 M for month, 1 d for day and 1 h for hour
[dateFormatter setDateFormat:@"M/d/yyyy h:mm:ss a"]; 
NSDate *currentDate = [dateFormatter dateFromString:currentDateString];

NSLog(@"current date: %@", currentDate);
//Example of the format using the actual date
NSLog(@"%@", [dateFormatter stringFromDate:[NSDate date]]);
[dateFormatter release];

The reason it returns nil is because you are calling the wrong method, there is no T in your date string (characters inside of single quotes ' in are literals), and the PM is not "P.M.". Things that are not breaking it but are not completely correct is you are trying to parse the month as a minute and your date string can have a minimum of 1 digit month, day, and hour so you should not use 2 specifiers which would pad them if you were to create a string from the date. Try this:

NSString *currentDateString = @"8/5/2011 1:38:13 PM";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//Set the AM and PM symbols
[dateFormatter setAMSymbol:@"AM"];
[dateFormatter setPMSymbol:@"PM"];
//Specify only 1 M for month, 1 d for day and 1 h for hour
[dateFormatter setDateFormat:@"M/d/yyyy h:mm:ss a"]; 
NSDate *currentDate = [dateFormatter dateFromString:currentDateString];

NSLog(@"current date: %@", currentDate);
//Example of the format using the actual date
NSLog(@"%@", [dateFormatter stringFromDate:[NSDate date]]);
[dateFormatter release];
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文