带有夏令时的 NSDateFormatter 的时间字符串不正确 [英] Incorrect time string with NSDateFormatter with Daylight Saving Time

查看:58
本文介绍了带有夏令时的 NSDateFormatter 的时间字符串不正确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的应用程序中使用 CET 作为我的默认 timezone.在德国,Daylight 节约时间将从 2015 年 3 月 29 日开始.现在我正在做一些测试,看看我的日期是否会在未来正确转换.我用下面的代码来测试它.

I'm using CET as my default timezone in my application. In Germany Daylight saving time will start from 29 March 2015. Now I'm doing some testing to see if my dates will be converted correctly in the future. I used following code to test it.

NSTimeZone *timeZone = [NSTimeZone timeZoneWithAbbreviation:@"CET"];
[NSTimeZone setDefaultTimeZone:timeZone];

NSDate *now = [NSDate date]; // 10 Feb, 2015
NSDate *dateAfter29March = [now dateByAddingMonths:2]; // 10 April, 2015

NSDateFormatter *formatter = [NSDateFormatter new];
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss ZZZ"];
[formatter setTimeZone:timeZone];

NSLog(@" NOW DATE -> %@",[formatter stringFromDate:now]);
NSLog(@" DATE AFTER 29 March -> %@",[formatter stringFromDate:dateAfter29March]);

添加月份的类别方法是

- (NSDate *)dateByAddingMonths:(NSInteger) dMonths {
    NSDateComponents *components = [[NSDateComponents alloc] init];
    components.month = dMonths;
    NSCalendar *calendar = [NSCalendar currentCalendar];
    return [calendar dateByAddingComponents:components toDate:self options:0];
}

控制台输出如下:

NOW DATE -> 2015-02-10 18:28:05 +0100
DATE AFTER 29 March -> 2015-04-10 18:28:05 +0200

我在 3 月 29 日之后的预期约会时间是 17:28:05,因为现在比白天少了一个小时.我究竟做错了什么?

Where my expected time on date after 29 March was 17:28:05 as One hour in now less after daylight time. What am I doing wrong?

PS:我也尝试在标签中设置输出字符串,但没有发生任何变化.

PS: I also tried to set the output strings in a label and no change occurs.

推荐答案

我真的不明白你在抱怨什么.

I really don't see what you are complaining about.

您要求操作系统将日期添加两个月.加上两个月意味着它使用日历,并返回两个月后的同一天同一时间的日期.它应该考虑到 DST 的变化,而且确实如此.这就是增加两个月的意思.

You asked the OS to add two months to a date. And adding two months means that it uses the calendar, and returns a date that is two months later, on the same day of the month, at the same time. It should take changes in DST into account, and it does. That's what adding two months means.

想象一下,我们总是在每个月的第一天上午 10 点开会.您希望在早上 10 点开会,无论是否为夏令时.

Imagine we have a meeting that we always do at the first of the month, at 10am in the morning. You want that meeting at 10am in the morning, whether it is DST or not.

这篇关于带有夏令时的 NSDateFormatter 的时间字符串不正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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