Zsub
Zsub

Reputation: 1797

Calculating time until a given point in time in iOS

I want to know the difference in seconds between now and, say, the next wednesday, 14:00.

I have found that [NSDate date]; gives me the current time and date, and that an NSTimeInterval would typically be used for this purpose (and I would like to use this interval somewhere else, and the somewhere else wants an NSTimeInterval), so the code would look like this:

NSDate *now = [NSDate date];
NSDate *nextWednesday = ???;
// profit
NSTimeInterval secondsUntilNextWednesday = [nextWednesday timeIntervalSinceDate:now];

But how do I get the date of next wednesday?

Edit2: I sort of improved the method, I still pretty much don't like it, but it's a huge improvement. Also, it's much more reminiscent of my pseudo-attempt.

- (NSTimeInterval)secondsUntilNextWednesday
{
    NSCalendar *calendar = [NSCalendar currentCalendar];

    NSDate *today = [NSDate date];
    NSDateComponents *components = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate: today];
    // 17 == 15:00, seemingly. (timezones)
    [components setHour:17];
    [components setWeekday:4];
    NSDate *wednesday = [calendar dateFromComponents:components];
    NSTimeInterval secondsToWednesday = [wednesday timeIntervalSinceDate:today];
    // if secondsToWednesday is negative, it has already been wednesday, 15:00 (or 16:00 depending on DST)
    if (secondsToWednesday < 0)
    {
        secondsToWednesday += 604800;
    }
    return secondsToWednesday;
}

Upvotes: 0

Views: 1076

Answers (1)

Joris Kluivers
Joris Kluivers

Reputation: 12081

Apple provides a handy guide with all you need to know about dates: the Date and Time Programming Guide

You probably want to take a look at the classes NSDateComponents and NSCalendar.

See Calendars, Date Components, and Calendar Units > Creating a Date from Components in the guide for an example to create a date based on different known date components.

The guide also shows how to calculate based on date components to get to the next wednesday relative to the current date for example.

Upvotes: 1

Related Questions