为什么我的时区没有保存到NSDate中? [英] Why isn't my time zone being saved into my NSDate?

查看:89
本文介绍了为什么我的时区没有保存到NSDate中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须从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,即使我将其时区设置为"Europe/Budapest"也是如此.我该如何解决这个问题?

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(),则默认情况下该日期将显示为格林尼治标准时间(格林尼治标准时间比布达佩斯时间晚一小时)

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中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆