NSCalendar dateFromComponents:GMT时区而不是systemTimeZone [英] NSCalendar dateFromComponents: GMT timezone instead of systemTimeZone
问题描述
此代码
NSCalendar *calendar =[NSCalendar currentCalendar];
[gregorian setTimeZone:tz];
NSLog(@"%@", [gregorian timeZone]);
NSDateComponents *comp = [gregorian components:(NSYearCalendarUnit | NSMonthCalendarUnit) fromDate:[NSDate date]];
[comp setDay:info.day];
[comp setMonth:info.month];
[comp setYear:info.year];
[comp setHour:info.hour];
[comp setMinute:info.minute];
[comp setSecond:info.second];
[comp setTimeZone:tz];
NSLog(@"%@", [comp timeZone]);
NSLog(@"%@", [gregorian dateFromComponents:comp]);
在控制台中显示以下内容:
shows the following in console:
Europe/Moscow (MSKS) offset 14400 (Daylight)
Europe/Moscow (MSKS) offset 14400 (Daylight)
2011-08-31 20:00:00 +0000
因此,正确指定了日历和组件的时区,但 [gregorian dateFromComponents:comp]
返回错误时区(GMT)的NSDate值。
So, the timezone for calendar and components is specified correctly, but [gregorian dateFromComponents:comp]
returns NSDate value with wrong time zone (GMT).
我需要纠正什么才能获得合适的时区?
What do I need to correct to get proper timezone?
推荐答案
您看到的输出完全正常。如果您直接NSLog一个 NSDate
对象,您将获得 description
方法返回的任何内容,这是GMT表示的日期(但不是刻在石头上)。
The output you are seeing is perfectly normal. If you NSLog a NSDate
object directly, you will get whatever the description
method returns, which is the GMT representation of the date (but that is not carved in stone).
NSDate
对象不受时区限制。 NSDate
表示从参考日期开始计算的绝对时刻。例如,在撰写本文时,当前日期类似于 337035053.199801
(自参考日期起的秒数),可以表示为 2011-09 -06 20:50:53 GMT
或 2011-09-06 22:50:53 CEST
。两者都是相同日期的不同人类可读表示。
NSDate
objects are not subject to timezones. A NSDate
represents an absolute instant in time measured from a reference date. For example, at the time of writing, the current date is something like 337035053.199801
(seconds since reference date), which can be represented as 2011-09-06 20:50:53 GMT
or 2011-09-06 22:50:53 CEST
. Both are different human readable representations of the same date.
总之,您需要什么来获得正确的时区?您需要使用 NSDateFormatter
在您喜欢的任何时区获取 NSDate
的字符串表示。
In conclusion, what do you need to get the proper timezone? You need to use NSDateFormatter
to get a string representation of your NSDate
in any timezone you like.
这篇关于NSCalendar dateFromComponents:GMT时区而不是systemTimeZone的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!