Objective-C Tips & Trick - Prioregroup.com
[Objective-C] Time difference between two dates
       
back

@interface NSDate (TimeDifference)

+ (NSDate*)dateWithString:(NSString*)dateString;
+ (NSString *)timeFormatted:(int)totalSeconds

@end

@implementation NSDate (TimeDifference)

+ (NSDate*)dateWithString:(NSString*)dateString;
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    return [formatter dateFromString:dateString];
}

+ (NSString *)timeFormatted:(int)totalSeconds
{
    int seconds = totalSeconds % 60;
    int minutes = (totalSeconds / 60) % 60;
    int hours = totalSeconds / 3600;
    return [NSString stringWithFormat:@"%02d:%02d:%02d",hours, minutes, seconds];
}

@end

NSDate *date1 = [NSDate dateWithString:@"2014-03-14 17:10:00"];
NSDate *date2 = [NSDate dateWithString:@"2014-03-15 05:00:10"];
NSTimeInterval seconds = [date2 timeIntervalSinceDate:date1];
NSLog(@"%@", [NSDate timeFormatted:seconds]);






Copyright © 1996-2018 Centro Studi Informatica di Danilo Priore. All rights reserved. P.I.10149810581.
prioregroup.com