Jos*_*osh 10 nsdate nstimezone nscalendar ios
我正在尝试使用日期并在将来创建日期,但夏令时不断妨碍我的时间.
这是我的代码,以移动到下个月的第一天的午夜约会:
+ (NSDate *)firstDayOfNextMonthForDate:(NSDate*)date
{
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    calendar.timeZone = [NSTimeZone systemTimeZone];
    calendar.locale = [NSLocale currentLocale];
    NSDate *currentDate = [NSDate dateByAddingMonths:1 toDate:date];
    NSDateComponents *components = [calendar components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit
                                                    fromDate:currentDate];
    [components setDay:1];
    [components setHour:0];
    [components setMinute:0];
    [components setSecond:0];
    return [calendar dateFromComponents:components];
}
+ (NSDate *) dateByAddingMonths: (NSInteger) monthsToAdd toDate:(NSDate*)date
{
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    calendar.timeZone = [NSTimeZone systemTimeZone];
    calendar.locale = [NSLocale currentLocale];
    NSDateComponents * months = [[NSDateComponents alloc] init];
    [months setMonth: monthsToAdd];
    return [calendar dateByAddingComponents: months toDate: date options: 0];
}
这给出了我在日期迭代运行方法的日期:
2013-02-01 00:00:00 +0000
2013-03-01 00:00:00 +0000
2013-03-31 23:00:00 +0000 should be 2013-04-01 00:00:00 +0000
2013-04-30 23:00:00 +0000 should be 2013-05-01 00:00:00 +0000
我最初的想法是不使用,systemTimeZone但似乎没有什么区别.关于如何使时间保持恒定而不考虑夏令时变化的任何想法?
对于给定的日历日期/时间,通常不可能预测表示的实际时间(自纪元以来的秒数).时区更改,DST规则更改.这是生活中的事实.夏令时在澳大利亚历史悠久.DST规则在以色列非常难以预测.DST规则最近在美国发生了变化,给微软带来了巨大的麻烦,因为微软存储了秒而非日历日期.
永远不要保存NSDate你的意思NSDateComponents.如果您的意思是"2013年5月1日在伦敦",那么请在您的数据库中保存"2013年5月1日在伦敦".然后计算出NSDate尽可能接近实际事件的关闭.NSDateComponents如果您关心日历事物(如月份),请使用所有日历数学.NSDate如果你真的只关心秒钟,那就做数学.
编辑:有关许多非常有用的背景信息,请参阅日期和时间编程指南.
还有一个关于日历组件的旁注:当我说"2013年5月1日在伦敦"时,这并不意味着"5月1日午夜".不要添加您实际上并不意味着的日历组件.
| 归档时间: | 
 | 
| 查看次数: | 2515 次 | 
| 最近记录: |