Skip to content

Instantly share code, notes, and snippets.

@krishashok
Created December 17, 2013 10:09
Show Gist options
  • Save krishashok/8002711 to your computer and use it in GitHub Desktop.
Save krishashok/8002711 to your computer and use it in GitHub Desktop.
Category on NSDate to get current time in current timezone (instead of GMT) and also set time component of date to midnight (useful in comparing dates for "same day" situations)
#import "NSDate+DateExtensions.h"
@implementation NSDate (DateExtensions)
+ (NSDate *) currentDateInSystemTimezone
{
NSDate* sourceDate = [NSDate date];
NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
NSTimeZone* destinationTimeZone = [NSTimeZone systemTimeZone];
NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:sourceDate];
NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:sourceDate];
NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;
NSDate* destinationDate = [[NSDate alloc] initWithTimeInterval:interval sinceDate:sourceDate];
return destinationDate;
}
- (NSDate *)dateAtBeginningOfDayForDate:(NSDate *)inputDate
{
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier: NSGregorianCalendar];
NSDateComponents *components = [gregorian components: NSUIntegerMax fromDate: inputDate];
[components setHour: 0];
[components setMinute: 0];
[components setSecond: 0];
NSDate *sourceDate = [gregorian dateFromComponents: components];
NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
NSTimeZone* destinationTimeZone = [NSTimeZone systemTimeZone];
NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:sourceDate];
NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:sourceDate];
NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;
NSDate* destinationDate = [[NSDate alloc] initWithTimeInterval:-interval sinceDate:sourceDate];
return destinationDate;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment