自定义日期字符串到NSDate

时间:2016-08-01 11:41:50

标签: objective-c nsdateformatter

我正在尝试将Mon, 01 Aug 2016 04:15 PM IST转换为NSDate

我尝试使用下面的代码但总是坚持使用nil。请帮忙

 NSString *fullTime = @"Mon, 01 Aug 2016 04:15 PM IST";
 NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
 [dateFormatter setDateFormat:@"EEE, dd MMM yyyy hh:mm a ZZZ"];
 NSDate *tempTime = [dateFormatter dateFromString:fullTime];

2 个答案:

答案 0 :(得分:2)

您的主要问题是日期ISTIST不是标准,可代表许多time zones

  

IST印度标准时间UTC + 05:30

     

IST爱尔兰标准时间UTC + 01

     

IST以色列标准时间UTC + 02

日期格式化程序无法正确格式化日期,因为它不知道哪个时区是什么时候。

如果可以,您应该更改日期或从日期中删除IST部分。

此外,您还需要将日语格式设置添加到它知道日期字符串中使用哪种语言的日期格式化程序中。 对于英语,请使用en_US_POSIX:

dateFormatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];

答案 1 :(得分:1)

我尝试了你的代码。首先它给出了nil.Then我将LocaleIdentifier更改为en_IN,因为

  

IST代表以色列标准时间,印度标准时间也代表it indicates this

NSString *strDate = @"Mon, 01 Aug 2016 04:15 PM IST";
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"EEE, dd MMM yyyy HH:mm a zzz"];
dateFormat.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_IN"];
NSDate *dateStr = [dateFormat dateFromString:strDate];
NSLog(@"The date is - %@",dateStr);

打印结果

The date is - 2016-08-01 06:45:00 +0000

Convert between date formats in Objective-C