我必须在objective-c 中从NSString 初始化一个NSDate 对象.我是这样做的:
I must initialize an NSDate object from NSString in objective-c. I do it like this:
NSString *dateString = [[webSentence child:@"DateTime"].text stringByReplacingOccurrencesOfString:@"T" withString:@" "];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-mm-dd HH:mm:ss"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"Europe/Budapest"]];
NSDate *date = [[NSDate alloc] init];
date = [dateFormatter dateFromString:dateString];
例如:当我尝试使用字符串值 @"2011-01-02 17:49:54" 时,我得到一个 NSDate 2011-01-02 16:49:54 +0000.如您所见,这两个值之间存在一小时的差异.NSDate 的值错误,它应该与我在 dateFormatter 中设置的时区中的字符串中定义的完全相同.即使我将其时区设置为欧洲/布达佩斯",它似乎也使用我将其定义为 UTC 的日期字符串.我该如何解决这个问题?
E.g: when I try it with string value @"2011-01-02 17:49:54" I get an NSDate 2011-01-02 16:49:54 +0000. As you can see there is a one hour difference between the two values. NSDate has a wrong value, it should be exactly the same I defined in my string in the timezone I set in dateFormatter. It seems it uses my date defined it string as UTC, even if I set its timezone to "Europe/Budapest". How can I fix this problem?
谢谢!
两件事:
1) 您的日期格式字符串有错误.您应该使用 MM
表示月份,而不是 mm
(小写 mm 表示分钟)
1) you have an error in your date format string. You should use MM
for month, not mm
(lowercase mm is for minutes)
2) 创建 NSDate 对象后,您需要使用 NSDateFormatter 方法 stringFromDate:
生成本地化到特定时区的日期字符串.如果您只是在 NSDate 对象上直接执行 NSLog(),它将默认将日期显示为 GMT(GMT 比布达佩斯时间晚一小时)
2) after you create you NSDate object, you'll need to use the NSDateFormatter method stringFromDate:
to generate a date string localized to a particular timezone. If you just do a straight NSLog() on the NSDate object it will show the date as GMT by default (GMT is one hour behind Budapest time)
这篇关于为什么我的时区没有保存到我的 NSDate 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!