我有一个像这样的 NSString
:@"3/15/2012 9:15 PM"
我想把它转换成 NSDate代码>,我是这样做的:
I have an NSString
like this: @"3/15/2012 9:15 PM"
and I would like to convert it to NSDate
, I have done like this:
NSString *str =@"3/15/2012 9:15 PM";
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
[formatter setDateFormat:@"mm/dd/yyyy HH:mm"];
NSDate *date = [formatter dateFromString:];
NSLog(@"%@", date); // date = null
你能帮帮我吗,谢谢.
使用如下解决方案
NSString *str = @"3/15/2012 9:15 PM";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"MM/dd/yyyy HH:mm a";
NSDate *date = [formatter dateFromString:str];
NSLog(@"%@", date);
对不起,格式应该如下:
Sorry, the format should be as follows:
formatter.dateFormat = @"MM/dd/yyyy hh:mm a";
显示的时间将是格林威治标准时间.因此,如果您添加/减去时区,将是晚上 9:15.
And the time shown will be GMT time. So if you add/subtract the timezone, it would be 9:15 PM.
#2
如下使用.你也会得到准确的时间.
Use as below. You would get exact time too.
NSString *str = @"3/15/2012 9:15 PM";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"MM/dd/yyyy hh:mm a";
NSTimeZone *gmt = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
formatter.timeZone = gmt;
NSDate *date = [formatter dateFromString:str];
NSLog(@"%@",date);
这篇关于从字符串创建 NSDate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!