119

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

4

9 回答 9

242
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 的时间实现不考虑闰秒,因此如果您需要这样的准确性,您将需要滚动您自己的实现。

于 2010-12-06T23:58:55.973 回答
85

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

NSDateComponents *components;
NSInteger days;

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

我相信这种方法可以解决诸如跨越夏令时变化的日期之类的情况。

于 2010-12-07T03:15:49.663 回答
25
NSTimeInterval diff = [date2 timeIntervalSinceDate:date1]; // in seconds

在哪里date1date2NSDate的。

另外,请注意 的定义NSTimeInterval

typedef double NSTimeInterval;
于 2010-12-06T23:00:07.513 回答
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 @""; 
}
于 2015-09-18T09:43:41.793 回答
3

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


#1。使用Calendar'sdateComponents(_: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。使用DateComponentsFormatter'sstring(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")
于 2019-02-01T00:32:23.920 回答
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)")

斯威夫特 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)
于 2017-05-15T11:13:39.850 回答
0

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

于 2016-04-25T05:08:17.100 回答
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
于 2020-04-24T15:12:23.897 回答
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];
}

于 2020-09-17T18:52:52.613 回答