1

"31-Dec-2010 9:00AM to 1:00PM"

Take the above NSString for example, I need to convert it to 2 NSDates e.g. 31-Dec-2010 9:00AM AND 31-Dec-2010 1:00PM

Then compare it with the current Date to see if the current date falls within the given dates.

So 31-Dec-2010 10:00AM would fall within.

I'm wondering What are the best practices/tricks are with Objective C to do this elegantly?

David van Dugteren
  • 3,879
  • 9
  • 33
  • 48
  • For comparison I like converting to unixtime (this is built into obj-c) but that just my preference! – ingh.am Jan 05 '11 at 23:57
  • I always get have to think longer than I want to when reading code that uses NSDate's compare: method, so I wrote a category on NSDate that implemented lessThan:, lessThanOrEqual:, etc. that uses compare: underneath. I find it much easier to read when coding. – nall Jan 06 '11 at 01:39

2 Answers2

2

As it turns out, NSDateFormatter has a dateFromString method, which does exactly what you want.

http://blog.evandavey.com/2008/12/how-to-convert-a-string-to-nsdate.html

The official documentation for NSDateFormatter:

http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSDateFormatter_Class/Reference/Reference.html

FeifanZ
  • 16,250
  • 7
  • 45
  • 84
0

I ended up doing it like so:

    NSString *temp = [[dateString allValues] objectAtIndex:0];

    NSLog(@"temp: %@", temp);


    NSArray *tokens = [temp componentsSeparatedByString: @" "];


    NSArray *tokenOneDelimited =  [[tokens objectAtIndex:0] componentsSeparatedByString: @"-"];


    NSString *dateStr1 = [NSString stringWithFormat: @"%@-%@-%@ %@",    [tokenOneDelimited  objectAtIndex:2],
                                                                        [tokenOneDelimited  objectAtIndex:1],
                                                                        [tokenOneDelimited  objectAtIndex:0],
                                                                        [tokens             objectAtIndex:1]];

    NSString *dateStr2 = [NSString stringWithFormat: @"%@-%@-%@ %@",    [tokenOneDelimited  objectAtIndex:2],
                          [tokenOneDelimited    objectAtIndex:1],
                          [tokenOneDelimited    objectAtIndex:0],
                          [tokens               objectAtIndex:3]];

    NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];

    [dateFormatter setDateFormat:@"yyyy-MMM-dd hh:mma"];

    NSDate *myDate1 = [dateFormatter dateFromString: dateStr1];

    NSDate *myDate2 = [dateFormatter dateFromString: dateStr2];

    NSDate *currentDate = [NSDate date];

    NSComparisonResult comparison = [currentDate compare: myDate1];

    NSComparisonResult comparison2 = [currentDate compare: myDate2];


    if ( 
        comparison      == NSOrderedDescending &&
        comparison2     == NSOrderedAscending
        )
    {
        NSLog(@"is On now");
David van Dugteren
  • 3,879
  • 9
  • 33
  • 48