ios 来自字符串的 NSDate
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12419205/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
NSDate from string
提问by NiKKi
I have a string "2012-09-16 23:59:59 JST" I want to convert this date string into NSDate.
我有一个字符串“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);
But it is not working. Its giving null value. Please help..
但它不起作用。它给出空值。请帮忙..
回答by danielbeard
When using 24 hour time, the hours specifier needs to be a capital H like this:
使用 24 小时制时,小时说明符需要是大写的 H,如下所示:
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss Z"];
Check here for the correct specifiers : http://unicode.org/reports/tr35/tr35-6.html#Date_Format_Patterns
在此处检查正确的说明符:http: //unicode.org/reports/tr35/tr35-6.html#Date_Format_Patterns
However, you need to set the locale for the date formatter:
但是,您需要为日期格式化程序设置语言环境:
// Set the locale as needed in the formatter (this example uses Japanese)
[dateFormat setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"ja_JP"]];
Full working code:
完整的工作代码:
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]);
Outputs (In GMT):
输出(格林威治标准时间):
Captured Date 2012-09-16 14:59:59 +0000
回答by Mil0R3
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);
回答by AppleDelegate
NSString *dateString = @"01-02-2010";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
// this is imporant - we set our input date format to match our input string
// if format doesn't match you'll get nil from your string, so be careful
[dateFormatter setDateFormat:@"dd-MM-yyyy"];
NSDate *dateFromString = [[NSDate alloc] init];
// end
dateFromString = [dateFormatter dateFromString:dateString];
[dateFormatter release];