开发者

Is current NSDate in local timezone within range of start and end NSDates in another timezone?

I need to determine if a user's current NSDate (local time zone) falls in the range of two NSDates belonging to other time zones.

For example:

I'm in California, and it's 20:00 PST. A coffee shop in New York is open between 08:00 and 00:00 EST. The coffee shop is stored as those exact values and sent in the XML along with the tz field indicating America/New_York.

I need to be able to determine if the coffee shop is open or not in the world currently. In this example, since it's only 23:00 EST in New York, then it would be open still.

I've tried using NSDate, NSTimeZone, NSCalendar, NSDateComponents to construct an algorithm to convert, but I've been uns开发者_开发技巧uccessful, and I just when I think I understand it, I get confused again. NSDate has no concept of timezone, so I can't figure out what real value exists in it, since you need to pass time zones to NSDateFormatter to see.

How would you create a method to determine if [NSDate date] in [NSTimeZone localTimeZone] is between the two NSDates in the other time zone?


NSDate represents a single instance in time, irrespective of time zones, calendars, etc.

All you need to do is compare a date to two other dates to see if it lies between them.

It sounds like your problem is actually getting the actual dates to compare, which isn't too hard. This is just a top of my head sample.

NSCalendar *calendar = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
calendar.timeZone = [NSTimeZone timeZoneWithName:@"America/New_York"];

NSDateComponents *components = [[[NSDateComponents alloc] init] autorelease];
components.year = 2011;
...
components.hour = 8;
NSDate *opening = [calendar dateFromComponents:components];
components.day = components.day + 1;
components.hour = 0;
NSDate *closing = [calendar dateFromComponents:components];
NSDate *now = [NSDate date];

if ([opening compare:now] == NSOrderedAscending && [now compare:closing] == NSOrderedAscending) {
  // do stuff
}

Alternatively, it might be easier if you convert the current time to the target time zone's date components and examine the hour component. This way you don't need to deal with making sure values in the date components are not out of range. Plus, it is not straightforward to compute the opening and closing date components in the general case.

NSCalendar *calendar = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
calendar.timeZone = [NSTimeZone timeZoneWithName:@"America/New_York"];
NSDate *now = [NSDate date];
NSDateComponents *components = [calendar components:NSHourCalendarUnit fromDate:now];

if (components.hour > 0 && components.hour < 8) {
  // do stuff
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜