获取两个日期之间的差异?

Get difference between two dates?

我在 24 小时内有两个约会,例如 (dd-MMM-yyyy HH:mm)。我想知道这两个日期之间的差异。

我的代码:这只是获取日期,我还想要天数和剩余时间(以小时为单位)。 (比如 6 天 5 小时)

    NSTimeInterval secondsBetween = [date2 timeIntervalSinceDate:date1];
    int numberOfDays = secondsBetween / 86400;
    NSLog(@"There are %d days in between the two dates.", numberOfDays);

Swift 3+

您可以使用日期组件,例如:

let date1 = Date()
let date2 = Date(timeIntervalSinceNow: 12345678)

let dateComponets = Calendar.current.dateComponents([.day, .hour], from: date1, to: date2)

那么您可以看到天数的差异:

debugPrint(dateComponets.day, dateComponets.hour) // 142 (days), 22 (hours)

ObjC

方法相同,但语法不同:

NSDate * date1 = [NSDate new];
NSDate * date2 = [NSDate dateWithTimeIntervalSinceNow:12345678];

NSDateComponents * dateComponents = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitHour fromDate:date1 toDate:date2 options:0];

那么天数相差:

NSLog(@"%d, %d", dateComponents.day, dateComponents.hour); // 142 (days), 22 (hours)

NSDateComponentsFormatter可以做到

NSTimeInterval secondsBetween = [date2 timeIntervalSinceDate:date1];
NSDateComponentsFormatter *formatter = [[NSDateComponentsFormatter alloc] init];
formatter.allowedUnits = NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute;
formatter.unitsStyle = NSDateComponentsFormatterUnitsStyleFull;
NSLog(@"%@", [formatter stringFromTimeInterval:secondsBetween]);

其他样式见NSDateComponentsFormatterUnitsStyle

struct EventDate {
var monthYear: [String]?
var monthNumber: [String]?
var year: [String]?
var month: [String]?
init(monthYear: [String]?,monthNumber:[String]?,year:[String]?,month:[String]?) {
    self.monthYear = monthYear
    self.monthNumber = monthNumber
    self.year = year
    self.month = month
}

}

func getMonthAndYearBetween(from start: String, to end: String) -> EventDate {

    var monthYear: [String] = []
    var monthNumber: [String] = []
    var years: [String] = []
    var months: [String] = []

    let format = DateFormatter()
    format.dateFormat = "dd/MM/yyyy"

    guard let startDate = format.date(from: start),
        let endDate = format.date(from: end) else {
            return EventDate(monthYear: [], monthNumber: [], year: [], month: [])
    }

    let calendar = Calendar(identifier: .gregorian)
    let components = calendar.dateComponents(Set([.month]), from: startDate, to: endDate)

    var allDates: [String] = []
    let dateRangeFormatter = DateFormatter()
    dateRangeFormatter.dateFormat = "MMM yyyy"

    for i in 0 ... (components.month! + 1) {
        guard let date = calendar.date(byAdding: .month, value: i, to: startDate) else {
            continue
        }

        let formattedDate = dateRangeFormatter.string(from: date)
        allDates += [formattedDate]

        let df = DateFormatter()
        df.dateFormat = "MMM yyyy"
        let monyr = df.string(from: date)
        monthYear.append(monyr)
        df.dateFormat = "MM"
        let monNO = df.string(from: date)
        monthNumber.append(monNO)
        df.dateFormat = "yyyy"
        let yr = df.string(from: date)
        years.append(yr)
        df.dateFormat = "MMM"
        let mon = df.string(from: date)
        months.append(mon)

    }
    return EventDate(monthYear: monthYear, monthNumber: monthNumber, year: years, month: months)
}

你可以这样

let eventDate = Date().getMonthAndYearBetween(from: startDate, to: endDate)