Srikar Appalaraju
Srikar Appalaraju

Reputation: 73718

iOS difference between 2 times

This is the situation here. I have current time in epoch. also I have number of days. I want to find the difference between the 2 to give some past time in epoch format. i.e.

currentEpochTime - (x days) to give some past time in epoch format.

This is what I have gotten so far -

+ (double)currTimeInEpoch
{
    NSDate *todayDate = [NSDate date];
    double ti         = [todayDate timeIntervalSince1970]*1000;
    return ti;    
}

+ (NSString *)timeDiff:(double)epoch diff:(double)diffInDays
{
    double past = epoch - (diffInDays * 24 * 60 * 60 * 1000);
    return [[NSNumber numberWithDouble:past] stringValue];
}

Is what I am doing correct? Not sure about it. Is there any simpler way to do this ?

Upvotes: 0

Views: 950

Answers (1)

Mark Adams
Mark Adams

Reputation: 30846

It's dangerous to go alone. Take this.

NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
dateComponents.day = -40; // Number of days to subtract
NSDate *newDate = [[NSCalendar autoupdatingCurrentCalendar] dateByAddingComponents:dateComponents toDate:[NSDate date] options:0];
NSTimeInterval newDateInEpochTime = [newDate timeIntervalSince1970] * 1000;

Upvotes: 2

Related Questions