[英]NSDate is off by one day?
I'm attempting to compare two dates together to decide how much time is between them. 我正在尝试比较两个日期,以确定它们之间有多少时间。 For some reason I keep getting it all by one day off.
出于某种原因,我一天之内都会得到一切。 I'm not too sure what is causing it, but I believe it to be the time zones?
我不太确定是什么原因造成的,但我相信这是时区吗? Do I have to specifically set that?
我需要专门设置吗?
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"MM/dd/yy"];
newAssignment.dueDate = [formatter stringFromDate:self.dueDatePicker.date];
NSDate *today = [NSDate date];
//Difference between dates test
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
int unitFlags = NSDayCalendarUnit;
NSDateComponents *comps = [gregorian components:unitFlags fromDate:today toDate:self.dueDatePicker.date options:0];
newAssignment.daysUntilAssignmentDueInt = [comps day];
//Test to compare dates
NSLog(@"\n\ntoday's date: %@\ndate picked: %@\ndue in: %d\n", today, self.dueDatePicker.date, newAssignment.daysUntilAssignmentDueInt);
My NSLog outputs: 我的NSLog输出:
today's date: 2013-11-03 03:17:26 +0000
date picked: 2013-11-05 04:17:12 +0000
due in: 1
I've gone so much as to think today's Daylight Savings change would be changing all of this. 我已经走了很多,以至于今天的夏令时更改将改变所有这些。 But I'm just not sure anymore.
但是我不确定。
EDIT: I've read a few other posts here on StackOverflow, but I can't seem to see anyone who is experiencing what I am. 编辑:我已经在StackOverflow上阅读了其他几篇文章,但是我似乎看不到有人在体验我的生活。
I've used nearly identical code to what you posted and I get correct results. 我使用了几乎与您发布的代码相同的代码,并且得到了正确的结果。
My code is a class method that relies on a global gregorian calendar that is set up in advance by the class's +initialize method, but the idea is the same. 我的代码是一个类方法,它依赖于该类的+ initialize方法预先设置的全局公历,但想法是相同的。 Here's my method:
这是我的方法:
+ (NSInteger) daysBetweenStartDate: (NSDate*) startDate andEndDate: (NSDate*) endDate;
{
NSDateComponents* dateComponents = [gregorian components: NSDayCalendarUnit fromDate: startDate toDate: endDate options: 0];
return dateComponents.day;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.