NSDate dateByAddingTimeInterval减去天数错误地更改时间 [英] NSDate dateByAddingTimeInterval subtracting days incorrectly changes time

查看:1119
本文介绍了NSDate dateByAddingTimeInterval减去天数错误地更改时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是否遗漏了一些关于NSDate dateByAddingTimeInterval如何与天工作的内容?这是我从特定日期(AIDate)减去33天的代码。 AIDate的时间值为00:00 PST。

Am I missing something about how NSDate dateByAddingTimeInterval works with days? Here is my code for subtracting 33 days from a specific date (AIDate). AIDate has a time value of 00:00 PST.

activityOne.ActivityDateTime = [AIDate dateByAddingTimeInterval:-33*24*60*60];

如果AIDate等于太平洋标准时间4-9-2013 00:00,则上述代码将减去33天和1小时工作到太平洋标准时间3-6-2013 23:00。

If the AIDate equals 4-9-2013 00:00 PST, the above code will subtract 33 days and 1 hour which works out to 3-6-2013 23:00 PST.

推荐答案

24 * 60 * 60表示24小时,而不是1天。
当你的计算超过夏令时或夏令时的变化时,这两者之间存在巨大差异。

24*60*60 means 24 hours, and not 1 day. There is a huge difference between those two when your calculation crosses the change from or to daylight saving time.

巧合33天前,您的时区没有夏令时。

Coincidentally 33 days ago there was no daylight saving time in your timezone.

执行此操作的正确方法是使用NSDateComponents。像这样:

The correct way to do this is to use NSDateComponents. Like this:

NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *offset = [[NSDateComponents alloc] init];
[offset setDay:-33];
NSDate *offsetedDate = [calendar dateByAddingComponents:offset toDate:[NSDate date] options:0];

这篇关于NSDate dateByAddingTimeInterval减去天数错误地更改时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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