Get difference between two dates?

前端 未结 3 1783
情话喂你
情话喂你 2021-01-29 06:10

I have two dates in 24 hours formate like (dd-MMM-yyyy HH:mm). I want to get a difference between these two dates.

My Code : This is getting only dates, I want a number

3条回答
  •  无人共我
    2021-01-29 06:58

    Swift 3+

    you can use date-components, like:

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

    then you can see the difference in days:

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

    ObjC

    same approach, but different syntax:

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

    then the difference in days:

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

提交回复
热议问题