DateMonger and TimeZone


#1

NSDate is always in UTC, so I wrote a helper function to convert UTC to local time.

main.m

[code]#import <Foundation/Foundation.h>
#import “NSDate+BNRDateConvenience.h”

int main(int argc, const char * argv[])
{

@autoreleasepool {
    
    NSDate *midnight = [NSDate midnightAtYear:2014 atMonth:7 atDay:25];
    NSLog(@"Midnight: %@", midnight);

}
return 0;

}[/code]

NSDate+BNRDateConvenience.h

[code]#import <Foundation/Foundation.h>

@interface NSDate (BNRDateConvenience)

  • (NSDate *)midnightAtYear:(NSInteger)year
    atMonth:(NSInteger)month
    atDay:(NSInteger)day;

@end[/code]

NSDate+BNRDateConvenience.m

[code]#import “NSDate+BNRDateConvenience.h”

/**

  • Helper function to display the local time
  • @param date
  • @return NSDate of local time
    */
    NSDate *localTime(NSDate *date)
    {
    NSTimeZone *timezone = [NSTimeZone defaultTimeZone];
    NSInteger seconds = [timezone secondsFromGMTForDate:date];
    return [NSDate dateWithTimeInterval:seconds sinceDate:date];
    }

@implementation NSDate (BNRDateConvenience)

  • (NSDate *)midnightAtYear:(NSInteger)year
    atMonth:(NSInteger)month
    atDay:(NSInteger)day
    {
    NSDateComponents *comps = [[NSDateComponents alloc] init];
    [comps setYear:year];
    [comps setMonth:month];
    [comps setDay:day];
    [comps setHour:0];
    [comps setMinute:0];
    [comps setSecond:0];

    NSCalendar *g = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDate *date = [g dateFromComponents:comps];

    return localTime(date);
    }

@end[/code]