NSDate 的自定义日期字符串

Custom date string to NSDate

我正在尝试将 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];

你的主要问题是日期中的ISTIST不是一个标准,可以代表很多time zones:

IST Indian Standard Time UTC+05:30

IST Irish Standard Time UTC+01

IST Israel Standard Time UTC+02

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

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

此外,您还需要向您知道在日期字符串中使用哪种语言的日期格式化程序添加语言环境。 对于英语最好使用 en_US_POSIX:

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

我试过你的 code.First 它给出 nil.Then 我将 LocaleIdentifier 更改为 en_IN 因为

IST stands for both Israel Standard Time, and India Standard Time also 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