How can I calculate the difference between two dates?

后端 未结 9 1382
渐次进展
渐次进展 2020-11-28 02:27

How can I calculate the days between 1 Jan 2010 and (for example) 3 Feb 2010?

9条回答
  •  醉话见心
    2020-11-28 03:20

    With Swift 5 and iOS 12, according to your needs, you may use one of the two following ways to find the difference between two dates in days.


    #1. Using Calendar's dateComponents(_:from:to:) method

    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. Using DateComponentsFormatter's string(from:to:) method

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

提交回复
热议问题