简体   繁体   中英

iPhone - Calculating the Day of Week of any date

I have a NSDate variable "aDate" that represents a date, for example, sunday, August 28, 2011. I have this date on a NSDate variable. This can be any date, but the problem appears when the day is a sunday.

I want to obtain the three letter string representing the day of week. In this case, SUN.

Then I have this code:

NSDateFormatter* theDateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[theDateFormatter setFormatterBehavior:NSDateFormatterBehavior10_4];
[theDateFormatter setDateFormat:@"EEE"];  
[theDateFormatter setLocale:currentLocale]; // I have tried to comment this out... no change

NSString *dayOfWeek =  [theDateFormatter stringFromDate:aDate];

the result I have is MON. Monday?

The insanity just goes wilder if I add this code:

NSCalendar *gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSDateComponents *comps = [gregorian components:NSWeekdayCalendarUnit fromDate:myDate];
int weekday = [comps weekday];

then weekday comes as 2 (MONDAY ??????) WTF? Confirming the problem.

I am on a locale that in theory monday is the first day of week. So, independently of my timezone any date just have one day of week. If I want to calculate what day of week was January 1, 1978, I shouldn't need to define any timezone.

How do I do that on iPhone?

thanks.

NSData is referenced to a base date "the first instant of 1 January 2001, GMT", it is simply the number of seconds since that base date.

Dates by definition are location sensitive, as I write this my friend in the UK is already in tomorrow.

Day of week is calendar sensitive.

Thus the timezone and calendar need to be specified. In my case they seem to be correct by default but are best specified explicitly.

So, set the timezone:

- (void)setTimeZone:(NSTimeZone *)tz

What's your time zone? Chances are you are one day off because your time zone is sufficiently different from GST that the time you are representing is the next or previous day.

I have found it necessary to specify the date as being in the local time zone to avoid this.

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