NSString 到 NSDate 的转换失败 [英] Conversion of NSString to NSDate failing
问题描述
我有以下一段代码..
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MM/dd/YYYY HH:mm"];
NSString *dateString = @"10/27/2012 18:00";
NSDate *parsedDate = [dateFormatter dateFromString:dateString] ;
NSLog(@"Parsed Date.. %@",[parsedDate description]);
我将 NSLog 语句设为 Parsed Date.. 2011-12-25 00:00:00 +0000
.我将不胜感激任何帮助解决此问题.我只想将该 NSString 转换为其 NSDate 等效项.也尝试使用 NSTimeZone ,但没有效果.我在这里错过了什么?
I am getting the NSLog statement as Parsed Date.. 2011-12-25 00:00:00 +0000
. I would appreciate any help in resolving this. I just want to convert that NSString to its NSDate equivalent. Tried using NSTimeZone as well, but no effect. What am I missing here?
推荐答案
您需要使用小写年份指示,yyyy
而不是 YYYY
>:
You need to use lower case year indication, yyyy
instead of YYYY
:
[dateFormatter setDateFormat:@"MM/dd/yyyy HH:mm"];
如果您想获得正确的时区,您需要设置 NSDateFormatter
的时区.默认情况下,它使用您设备的时区.对于格林威治标准时间,请使用以下内容.
If you want to get the timezone right you need to set the timezone of the NSDateFormatter
. By default it uses the timezone of your device. For the time at GMT use the following.
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
[dateFormatter setDateFormat:@"MM/dd/yyyy HH:mm"];
NSString *dateString = @"10/27/2012 18:00";
NSDate *parsedDate = [dateFormatter dateFromString:dateString] ;
NSLog(@"Parsed Date.. %@",[parsedDate description]);
这篇关于NSString 到 NSDate 的转换失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!