NSDate dateByAddingTimeInterval subtracting days incorrectly changes time

社会主义新天地 提交于 2020-01-01 03:21:08

问题


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];

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.


回答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.

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

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];



回答2:


you can do it with bellow code..

 NSDateComponents *dc = [[NSCalendar currentCalendar] components:NSDayCalendarUnit|NSMonthCalendarUnit|NSYearCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit|NSQuarterCalendarUnit fromDate:yourDate];
 [dc setDay:dc.day - 33];
 NSDate *noticeDate = [[NSCalendar currentCalendar] dateFromComponents:dc];

i hope this is helpful to you...



来源:https://stackoverflow.com/questions/15916673/nsdate-datebyaddingtimeinterval-subtracting-days-incorrectly-changes-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!