这是使用 NSDateComponents 向 NSDate 添加天数的正确方法吗?
我正在使用下面的方法从 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);
return newDate; }
案例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 小时。这里可能存在什么问题? 有人遇到过这个问题吗?
I am using below method to add or subtract days from an NSDate.
When I logged the values I get an unexpected result at times.
Here is one of the case:
//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);
return newDate;
}
CASE 1:
2012-02-17 06:28:14.474 Application[2906:707] start Date : 2012-03-08 11:26:23 +0000 End Date 2012-03-09 11:26:23 +0000 Number of days 1
CASE 2:
2012-02-17 06:29:00.631 Application[2906:707] start Date : 2012-03-10 11:26:23 +0000 End Date 2012-03-11 10:26:23 +0000 Number of days 1
In case 1, when I added a single day to 2012-03-08 11:26:23 +0000, I get 2012-03-09 11:26:23 +0000.
But when I add a single day to 2012-03-10 11:26:23 +0000 I get 2012-03-11 10:26:23 +0000.
1 hour is additionally reduced. What could be the problem here?
Is any one have faced this problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是因为夏令时 - 美国夏令时从 3 月 11 日开始。
编辑:
您可以通过将输入的日期转换为日期组件对象,更改日期组件(时间不受影响)然后转换回 NSDate 来解决此问题。
It's because of daylight savings times - US daylight savings starts on 11th March.
Edit:
You can solve it by converting the inputted date into a date components object, change the day component (time is unaffected) and then convert back into an
NSDate
.