我正在尝试比较两天的NSDate对象,我在第一次使用NSDateComponents来计算我的两个日期对象之间的差异,但它运行正常。
NSString *dateStr =@"2012-11-05 15:00:00";
NSDate *date = [dateFormat dateFromString:dateStr];
NSDateComponents *datesDiff = [calendar components: NSDayCalendarUnit
fromDate: date
toDate: [NSDate date]
options: 0];
这不能解决我的问题。实际上,当date1 = 2012-11-05 23:00:00和date2 = 2012-11-06 10:00:00时,两个日期之间的差异是0天和11小时。 我正在寻找能让我发现日期变化的东西,换句话说,当date1 = 2012-11-05 23:00:00和date2 = 2012-11-06 00:01:00时,有一天的差异。
如果有人知道解决方案,我会欢迎他的建议。 提前致谢
答案 0 :(得分:19)
我认为你正在寻找这个(来自Date and Time Programming Guide):
清单13两个日期之间的天数,作为
之间的中间夜数
@implementation NSCalendar (MySpecialCalculations)
-(NSInteger)daysWithinEraFromDate:(NSDate *) startDate toDate:(NSDate *) endDate
{
NSInteger startDay=[self ordinalityOfUnit:NSDayCalendarUnit
inUnit: NSEraCalendarUnit forDate:startDate];
NSInteger endDay=[self ordinalityOfUnit:NSDayCalendarUnit
inUnit: NSEraCalendarUnit forDate:endDate];
return endDay-startDay;
}
@end
编辑:Swift版本:
extension NSCalendar {
func daysWithinEraFromDate(startDate: NSDate, endDate: NSDate) -> Int {
let startDay = self.ordinalityOfUnit(.Day, inUnit: NSCalendarUnit.Era, forDate: startDate)
let endDay = self.ordinalityOfUnit(.Day, inUnit: NSCalendarUnit.Era, forDate: endDate)
return endDay - startDay
}
}
答案 1 :(得分:6)
NSString *start = @"2010-09-01";
NSString *end = @"2010-12-01";
NSDateFormatter *f = [[NSDateFormatter alloc] init];
[f setDateFormat:@"yyyy-MM-dd"];
NSDate *startDate = [f dateFromString:start];
NSDate *endDate = [f dateFromString:end];
[f release];
NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [gregorianCalendar components:NSDayCalendarUnit
fromDate:startDate
toDate:endDate
options:0];
[gregorianCalendar release];
组件现在有所不同。
NSLog(@"%ld", [components day]);
答案 2 :(得分:0)
func daysBetweenDates(startDate: NSDate, endDate: NSDate) -> Int
{
let calendar = NSCalendar.currentCalendar()
let components = calendar.components([.Day], fromDate: startDate, toDate: endDate, options: [])
return components.day
}
或
let calendar = NSCalendar.currentCalendar();
let component1 = calendar.component(.Day, fromDate: fromDate)
let component2 = calendar.component(.Day, fromDate: toDate)
let difference = component1 - component2
答案 3 :(得分:0)
对于Swift 3:
从@ masa的答案扩展:
extension Calendar {
func daysWithinEraFromDate(startDate: Date, endDate: Date) -> Int? {
guard let startDay = ordinality(of: .day, in: .era, for: startDate) else {
return nil
}
guard let endDay = ordinality(of: .day, in: .era, for: endDate) else {
return nil
}
return endDay - startDay
}
}