从字符串创建 NSDate [英] create a NSDate from a string

查看:7

问题描述

我有一个像这样的 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);
查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆