views:

141

answers:

4

I can not seem to figure out how to count the number of seconds to 6:00 pm for the current day. Need it to set the limit of a date picker so that the user can only pick a time from now until 6pm.

Working with NSDate seems to be painful at best.

A: 

You can always fall back to C http://linux.die.net/man/3/mktime

Tuomas Pelkonen
I was considering that as a worse case. Not a fan of NSDate anymore.
oden
+4  A: 

You can use NSCalendar class to perform some calculations for you. Code may look like:

NSCalendar* calendar = [NSCalendar currentCalendar];
NSDateComponents* comps = [calendar components: NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:[NSDate date]];
[comps setHour: 18];
[comps setMinute: 0];
[comps setSecond: 0];
NSDate *pmDate = [calendar dateFromComponents:comps];
NSTimeInterval interval = [pmDate timeIntervalSinceNow];
Vladimir
NSTimeInterval is a double, casting this across to an int gave me the result. Thank you :)8 lines of code to count the number of seconds until 6pm... and I thought my wife was verbose.
oden
A: 

Hmm.. you could create a NSDate object with the time of 6 pm and use it's function timeIntervalSinceNow. This gives you the amount of seconds between now and 6-PM

antihero
I did try this but I found that the date was needed to be passed and then the time. Could not figure out how to do it.
oden
A: 

You could try something like this (from iphonedevsdk.com):

//NSDate_ext.h

#import <Foundation/Foundation.h>

@interface NSDate (Extend)
- (BOOL)isBetween:(NSDate *)dateStart:(NSDate *)dateEnd;
@end

//NSDate_ext.m

#import "NSDate_ext.h"

@implementation NSDate (Extend)

- (BOOL)isBetween:(NSDate *)dateStart:(NSDate *)dateEnd {

    if ([self compare:dateEnd] == NSOrderedDescending)
        return NO;

    if ([self compare:dateStart] == NSOrderedAscending) 
        return NO;

    return YES;
}

@end

Check if the user's entered time is between the date range you specify.

christo16
Sorry this is a UI experience issue, need to change the viewable time range in the slider.Thanks anyway.
oden