我如何计算两个日期之间的差额?

如何计算2010年1月1日至(例如)2010年2月3日期间的日数?

116165 次浏览
NSTimeInterval diff = [date2 timeIntervalSinceDate:date1]; // in seconds

其中 date1date2NSDate

另外,请注意 NSTimeInterval的定义:

typedef double NSTimeInterval;
NSDate *date1 = [NSDate dateWithString:@"2010-01-01 00:00:00 +0000"];
NSDate *date2 = [NSDate dateWithString:@"2010-02-03 00:00:00 +0000"];


NSTimeInterval secondsBetween = [date2 timeIntervalSinceDate:date1];


int numberOfDays = secondsBetween / 86400;


NSLog(@"There are %d days in between the two dates.", numberOfDays);

编辑:

请记住,NSDate对象代表精确的时刻,它们没有任何相关的时区信息。当您使用例如 NSDateFormatter将字符串转换为日期时,NSDateFormatter将从配置的时区转换时间。因此,两个 NSDate对象之间的秒数将是 一直都是时区无关的。

此外,这份文件指定 Cocoa 的时间实现不考虑闰秒,因此如果需要这样的准确性,则需要滚动自己的实现。

你可能想使用这样的东西:

NSDateComponents *components;
NSInteger days;


components = [[NSCalendar currentCalendar] components: NSDayCalendarUnit
fromDate: startDate toDate: endDate options: 0];
days = [components day];

我相信这个方法可以解释日期这样的情况,这些日期跨越了夏时制的变化。

看看这个。它使用 iOS 日历来计算日光节约和闰年。可以将字符串和条件更改为包含带有小时和天的分钟。

+(NSString*)remaningTime:(NSDate*)startDate endDate:(NSDate*)endDate
{
NSDateComponents *components;
NSInteger days;
NSInteger hour;
NSInteger minutes;
NSString *durationString;


components = [[NSCalendar currentCalendar] components: NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute fromDate: startDate toDate: endDate options: 0];


days = [components day];
hour = [components hour];
minutes = [components minute];


if(days>0)
{
if(days>1)
durationString=[NSString stringWithFormat:@"%d days",days];
else
durationString=[NSString stringWithFormat:@"%d day",days];
return durationString;
}
if(hour>0)
{
if(hour>1)
durationString=[NSString stringWithFormat:@"%d hours",hour];
else
durationString=[NSString stringWithFormat:@"%d hour",hour];
return durationString;
}
if(minutes>0)
{
if(minutes>1)
durationString = [NSString stringWithFormat:@"%d minutes",minutes];
else
durationString = [NSString stringWithFormat:@"%d minute",minutes];


return durationString;
}
return @"";
}

您可以通过转换日期(以秒为单位)并采用自1970年以来的时间间隔来找到这个差异,然后您可以找到两个日期之间的差异。

Swift 4
试试这个并查看(使用 String 的日期范围) :

// Start & End date string
let startingAt = "01/01/2018"
let endingAt = "08/03/2018"


// Sample date formatter
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy"


// start and end date object from string dates
var startDate = dateFormatter.date(from: startingAt) ?? Date()
let endDate = dateFormatter.date(from: endingAt) ?? Date()




// Actual operational logic
var dateRange: [String] = []
while startDate <= endDate {
let stringDate = dateFormatter.string(from: startDate)
startDate = Calendar.current.date(byAdding: .day, value: 1, to: startDate) ?? Date()
dateRange.append(stringDate)
}


print("Resulting Array - \(dateRange)")

Swift 3

var date1 = Date(string: "2010-01-01 00:00:00 +0000")
var date2 = Date(string: "2010-02-03 00:00:00 +0000")
var secondsBetween: TimeInterval = date2.timeIntervalSince(date1)
var numberOfDays: Int = secondsBetween / 86400
print(numberOfDays)

使用 Swift 5和 iOS 12,根据您的需要,您可以使用以下两种方法之一来找出两个日期之间的差异。


# 1. 使用 CalendardateComponents(_:from:to:)方法

import Foundation


let calendar = Calendar.current


let startDate = calendar.date(from: DateComponents(year: 2010, month: 11, day: 22))!
let endDate = calendar.date(from: DateComponents(year: 2015, month: 5, day: 1))!


let dateComponents = calendar.dateComponents([Calendar.Component.day], from: startDate, to: endDate)


print(dateComponents) // prints: day: 1621 isLeapMonth: false
print(String(describing: dateComponents.day)) // prints: Optional(1621)

2. 使用 DateComponentsFormatterstring(from:to:)方法

import Foundation


let calendar = Calendar.current


let startDate = calendar.date(from: DateComponents(year: 2010, month: 11, day: 22))!
let endDate = calendar.date(from: DateComponents(year: 2015, month: 5, day: 1))!


let formatter = DateComponentsFormatter()
formatter.unitsStyle = .full
formatter.allowedUnits = [NSCalendar.Unit.day]


let elapsedTime = formatter.string(from: startDate, to: endDate)
print(String(describing: elapsedTime)) // prints: Optional("1,621 days")

要找到差异,您需要获取当前日期和将来的日期。在下面的例子中,我使用2天作为将来日期的示例。计算方法:

2 days * 24 hours * 60 minutes * 60 seconds. We expect the number of seconds in 2 days to be 172,800.

// Set the current and future date
let now = Date()
let nowPlus2Days = Date(timeInterval: 2*24*60*60, since: now)


// Get the number of seconds between these two dates
let secondsInterval = DateInterval(start: now, end: nowPlus2Days).duration


print(secondsInterval) // 172800.0

如果你想要所有的单位,而不仅仅是最大的单位,使用以下两种方法中的一种(基于@Ankish 的回答) :

示例输出: 28 D | 23 H | 59 M | 59 S

+ (NSString *) remaningTime:(NSDate *)startDate endDate:(NSDate *)endDate
{
NSCalendarUnit units = NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
NSDateComponents *components = [[NSCalendar currentCalendar] components:units fromDate: startDate toDate: endDate options: 0];
return [NSString stringWithFormat:@"%ti D | %ti H | %ti M | %ti S", [components day], [components hour], [components minute], [components second]];
}


+ (NSString *) timeFromNowUntil:(NSDate *)endDate
{
return [self remaningTime:[NSDate date] endDate:endDate];
}