我使用下面的方法来添加或减去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; }
CASE 1:
2012-02-17 06:28:14.474申请[2906:707]开始日期:2012-03-08 11:26:23 0000结束日期2012-03-09 11:26:23 0000天数1
CASE 2:
2012-02-17 06:29:00.631申请[2906:707]开始日期:2012-03-10 11:26:23 0000结束日期2012-03-11 10:26:23 0000天数1
在案例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 10:26:23 0000 .
1 hour is additionally reduced. 这可能是什么问题?有人遇到过这个问题吗?
1 回答
这是因为夏令时 - 美国夏令时从3月11日开始 .
编辑:
您可以通过将输入的日期转换为日期组件对象,更改日期组件(时间不受影响)然后转换回
NSDate
来解决此问题 .