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

时间:2010-12-06 22:52:46

标签: objective-c swift date nsdate

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

8 个答案:

答案 0 :(得分:225)

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因此,两个{{1}}对象之间的秒数总是与时区无关。

此外,this documentation指定Cocoa的时间实现不考虑闰秒,因此如果您需要这样的准确性,则需要推出自己的实现。

答案 1 :(得分:80)

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

NSDateComponents *components;
NSInteger days;

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

我认为这种方法可以解决诸如夏令时变化的日期等情况。

答案 2 :(得分:23)

NSTimeInterval diff = [date2 timeIntervalSinceDate:date1]; // in seconds

其中date1date2NSDate

另外,请注意NSTimeInterval

的定义
typedef double NSTimeInterval;

答案 3 :(得分:19)

结帐。它使用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 @""; 
}

答案 4 :(得分:1)

Swift 4
试试这个并查看(带字符串的日期范围):

// 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)

答案 5 :(得分:0)

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

答案 6 :(得分:0)

要查找差异,您需要获取当前日期和将来的日期。在以下情况下,我以2天作为未来日期的示例。计算方式:

2 days * 24 hours * 60 minutes * 60 seconds。我们希望2天的秒数为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

答案 7 :(得分: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];
}