从NSDate获取小时组件 [英] getting hour component from an NSDate

查看:86
本文介绍了从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.

我知道这与NSTimezoneDST有关.但是我无法理解它!

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屋!

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