Home | About | Apps | Github | Rss

Comparing NSDates from different timezones

Comparing 2 NSDate’s is trivial, unless they are from different timezone, in which case one of them should be converted to the other timezone and then compared.

Here is a simple code snippet that I came up with. It gets the offset from GMT in seconds for both timezones and uses the delta to convert a date relative to the other timezone.

// Get time and time zone offset from GMT
NSDate *currentTime = [NSDate date];
NSInteger currentTZSec = [[NSTimeZone defaultTimeZone] secondsFromGMT];

NSDate *otherTime = info.otherTime;
NSInteger otherTZSec = [info.otherTimeZone secondsFromGMT];

// Get timezone delta difference in seconds
NSInteger deltaTZSec = currentTZSec - otherTZSec;

// Convert other time into current timezone
NSDate *otherTimeInUserTZ = [otherTime dateByAddingTimeInterval:deltaTZSec];

// Check if cancellation until time is past current user time
if ( [otherTimeInUserTZ compare:currentTime] == NSOrderedDescending ) {
	NSLog(@"currentTIme < otherTime");
} else {
	NSLog(@"currentTIme > otherTime");

More posts