简体   繁体   中英

How to comparison date with timezones on iOS

I looking for a way how to comparison date with timezones on ios. It is hard because NSDate uses only absolute timezone. I didn't find equivalent of DateTime from JodaTime library for iOS.

I would like to implement method:

- (BOOL)isTheSameDayForDate:(NSDate *)date1 withTimeZone:(NSTimeZone *)timeZone1 andDate:(NSDate *)date2 withTimeZone:(NSTimeZone *)timeZone2;

This method return true if date1 and date2 with their timezones are in the same day from timezone2 perspective.

For: 2014-10-09T03:00:00+03:00 and 2014-10-09T23:00:00+03:00 return YES.

For: 2014-10-09T00:03:00+03:00 and 2014-10-10T00:03:00+03:00 return NO.

It looks easy but please note that for:

2014-10-08T16:00:00-8:00 and 2014-10-09T1:00:00+02:00 return YES

2014-10-08T13:00:00-8:00 and 2014-10-09T1:00:00+02:00 return NO

You should use the new methods on NSCalendar that are designed for this purpose. Something like this:

NSDate *date1;
NSDate *date2;
NSTimeZone *myTimeZone; // zone of interest

// Set up dates and zone, then do this
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
[calendar setTimeZone:myTimeZone];
BOOL sameDay = [calendar isDate:date1 inSameDayAsDate:date2];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM