我正在使用下面的方法从NSDate中添加或减去天数。
当我记录这些值时,有时会得到一个意想不到的结果。
以下是其中一个案例:
//This adds X days to the current Date and returns to the user
+(NSDate*)getRelativeDateInDays:(NSInteger)days forDate:(NSDate*)date{
NSCalendar *gregorian = [[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *weekdayComponents = [[NSDateComponents alloc] init];
[weekdayComponents setDay:days];
NSDate *newDate = [gregorian dateByAddingComponents:weekdayComponents toDate:date options:0];
[gregorian release];
[weekdayComponents release];
NSLog(@"start Date : %@ End Date %@",date,newDate);
返回newDate;}
案例1:
2012-02-17 06:28:14.474申请2906:707开始日期: 2012-03-08 11:26:23 +0000
案例2:
2012-02-17 06:29:00.631申请2906:707开始日期: 2012-03-10 11:26:23 +0000
在案例1中,当我将一天的时间添加到2012-03-08 11:26:23 +0000时,我得到了2012-03-09 11:26:23 +0000。
但是当我把一天加到2012-03-10 11:26:23 +0000时,我得到了2012-03-11 :26:23 +0000。
1小时额外减少。这里有什么问题?是否有人曾面对这个问题?
发布于 2012-02-17 11:42:59
这是因为日光节约时代--美国的夏令储蓄从3月11日开始。
编辑:
您可以通过将输入的日期转换为date components对象,更改date组件(时间不受影响),然后转换回NSDate
来解决这个问题。
https://stackoverflow.com/questions/9327525
复制相似问题