开发者

Determining Day Components of an NSDate Object (Time Zone Issues)

How would I be able to determine if a certain NSDate object falls within a certain day? Since all dates calculate to the GMT time zone, a date maybe actually be on the 8th instead of the 9th, for example. What's the best way to account for the time zone difference when calculating things l开发者_开发技巧ike days, months, day of week, etc.


An NSDate is an absolute point in time. When you want to know which day it falls on, you have to consider your specific time zone. Since you get the NSDateComponents with an NSCalendar, you can use setTimeZone: on the calendar to get the components (month, day, hour etc.) for the time zone you're interested in.

If you deal with "calendar dates" (i.e. dates that should always represent a specific day/month and not an absolute point in time), you could always use a fixed time zone (e.g. GMT) to present the dates. NSDateFormatter (which you use for displaying dates to the user) also has a timeZone property.


You need to set the desired timezone in NSCalendar before using it to break the date into parts:

NSCalendar* gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
[gregorian setTimeZone:[NSTimeZone localTimeZone]]; // or timeZoneWithName:@"GMT" etc.

unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit;
NSDateComponents* compsDate = [gregorian components:unitFlags fromDate:date];
// [compsDate year] [compsDate month] [compsDate day] 
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜