xcode dateFromString 返回 nil
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6265162/
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
dateFromString returns nil
提问by mayuur
This is my NSString,
这是我的NSString,
myDate : 2011-06-07 11:23:47 0000
And this is the code,
这是代码,
NSTimeZone *currentDateTimeZone = [NSTimeZone defaultTimeZone];
NSDateFormatter *currentDateFormat = [[NSDateFormatter alloc]init];
[currentDateFormat setTimeZone:currentDateTimeZone];
[currentDateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss Z"];
NSDate *tempDate = [currentDateFormat dateFromString:second];
Still tempDategets the value nil
.
Can anyone help?
仍然tempDate获取值nil
。
任何人都可以帮忙吗?
采纳答案by Deepak Danduprolu
How did you get the date string? It needs to be 2011-06-07 11:23:47 +0000
for this to work.
你是怎么得到日期字符串的?这需要它2011-06-07 11:23:47 +0000
才能工作。
回答by Sujal
Try this, This is the function to get Date from String .
试试这个, 这是从 String 获取日期的函数。
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setFormatterBehavior:NSDateFormatterBehavior10_4];
[df setDateFormat:@"EEE, dd MMM yy HH:mm:ss"];
NSDate *convertedDate = [df dateFromString:stringDate];
[df release];
// [convertedDate description]
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setAMSymbol:@"AM"];
[formatter setPMSymbol:@"PM"];
[formatter setDateFormat:@"MM/dd/yyyy hh:mm:a"];
return [formatter stringFromDate:convertedDate];
回答by Zahur
What I think is, it not related to TimeZone but the device 24hours settings. Developer has to check if the device timings are of 24hours then they should use HH, and if the device timings are of 12hours then they should use hh.
我的想法是,它与 TimeZone 无关,而是与设备 24 小时设置有关。开发人员必须检查设备计时是否为 24 小时,则应使用 HH,如果设备计时为 12 小时,则应使用 hh。
回答by Viktor Apoyan
NSTimeZone *currentDateTimeZone = [NSTimeZone defaultTimeZone];
NSDateFormatter *currentDateFormat = [[[NSDateFormatter alloc]init] *autorelease*];
[currentDateFormat setTimeZone:currentDateTimeZone];
[currentDateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss *ZZZZ*"];
NSDate *tempDate = [currentDateFormat dateFromString:second];
Add autoreleaseand ZZZZinsead of Z.
在 Z 的基础上添加autorelease和ZZZZ。