从NSDate获取小时组件 [英] getting hour component from an NSDate
问题描述
我正在尝试从NSDate
获取小时部分.
这是我的工作:
I'm trying to get the hour component from an NSDate
.
Here is what I do:
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[calendar setTimeZone:[NSTimeZone timeZoneWithName:@"GMT+1"]];
NSDateComponents *startComponents = [calendar components:DATE_COMPONENTS fromDate:_start];
startComponents.timeZone = [NSTimeZone timeZoneWithName:@"GMT+1"];
int hours = [startComponents hour];
现在,昨天以前,hours value
总是比现在早一小时.但是从昨天开始,hours value
提前了2个小时.
Now before yesterday the hours value
always was one hour ahead. But since yesterday the hours value
was 2 hours ahead.
我知道这与NSTimezone
和DST
有关.但是我无法理解它!
I know this has something to do with the NSTimezone
and the DST
. But I can't get my head arround it!
有人可以帮我吗?
推荐答案
"GMT+1"
不被识别为时区名称,因此
"GMT+1"
is not recognized as a time zone name, so that
[NSTimeZone timeZoneWithName:@"GMT+1"]
是nil
,而是使用本地时区,它可能在您所在国家/地区的上周末从冬季(GMT + 01)切换为夏季(GMT + 02).
is nil
and the local time zone is used instead, which probably switched from Wintertime (GMT+01) to Summertime (GMT+02) last weekend in your country.
将"GMT+1"
替换为"GMT+01"
:
[NSTimeZone timeZoneWithName:@"GMT+01"]
// or alternatively:
[NSTimeZone timeZoneForSecondsFromGMT:3600]
工作并给出预期的结果.
works and gives the expected result.
请注意,只需设置NSCalendar
的时区即可.设定时区
在这种情况下NSDateComponents
的值无效.
Note that it is sufficent to set the time zone of the NSCalendar
. Setting the time zone
of the NSDateComponents
has no effect in this case.
这篇关于从NSDate获取小时组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!