How can I calculate the difference between two dates?

后端 未结 9 1353
渐次进展
渐次进展 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:28

    You can find the difference by converting the date in seconds and take time interval since 1970 for this and then you can find the difference between two dates.

    0 讨论(0)
  • 2020-11-28 03:29

    Checkout this out. It takes care of daylight saving , leap year as it used iOS calendar to calculate.You can change the string and conditions to includes minutes with hours and days.

    +(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 @""; 
    }
    
    0 讨论(0)
  • 2020-11-28 03:29

    To find the difference, you need to get the current date and the date in the future. In the following case, I used 2 days for an example of the future date. Calculated by:

    2 days * 24 hours * 60 minutes * 60 seconds. We expect the number of seconds in 2 days to be 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
    
    0 讨论(0)
提交回复
热议问题