来自字符串的NSDate

NiK*_*KKi 14 iphone ios

我有一个字符串"2012-09-16 23:59:59 JST"我想将这个日期字符串转换为NSDate.

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd hh:mm:ss Z"];
NSDate *capturedStartDate = [dateFormatter dateFromString: @"2012-09-16 23:59:59 JST"];
NSLog(@"%@", capturedStartDate);
Run Code Online (Sandbox Code Playgroud)

但它没有用.它给出了空值.请帮忙..

dan*_*ard 35

当使用24小时时,小时说明符需要是大写H,如下所示:

[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss Z"];
Run Code Online (Sandbox Code Playgroud)

在此处查看正确的说明符:http://unicode.org/reports/tr35/tr35-6.html#Date_Format_Patterns

但是,您需要为日期格式化程序设置区域设置:

// Set the locale as needed in the formatter (this example uses Japanese)
[dateFormat setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"ja_JP"]];
Run Code Online (Sandbox Code Playgroud)

完整的工作代码:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss zzz"];
[dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"ja_JP"]];
NSDate *capturedStartDate = [dateFormatter dateFromString: @"2012-09-16 23:59:59 JST"];
NSLog(@"Captured Date %@", [capturedStartDate description]);
Run Code Online (Sandbox Code Playgroud)

产出(格林尼治标准时间):

Captured Date 2012-09-16 14:59:59 +0000
Run Code Online (Sandbox Code Playgroud)


Mil*_*0R3 6

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss Z"];
NSDate *capturedStartDate = [dateFormatter dateFromString: @"2012-09-16 23:59:59 GMT-08:00"];
NSLog(@"%@", capturedStartDate);
Run Code Online (Sandbox Code Playgroud)