简体   繁体   English

iPhone-计算任何日期的星期几

[英]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. 我有一个代表日期的NSDate变量“ aDate”,例如,2011年8月28日,星期日。我在NSDate变量上有此日期。 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. 在这种情况下,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. 我得到的结果是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? 然后工作日为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. 如果要计算1978年1月1日是星期几,则不需要定义任何时区。

How do I do that on iPhone? 如何在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. NSData被称为基准日期“ GMT 2001年1月1日的第一时刻”,它只是该基准日期以来的秒数。

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. 您有一天放假的可能,因为您所在的时区与GST完全不同,因此您表示的时间是第二天或前一天。

I have found it necessary to specify the date as being in the local time zone to avoid this. 我发现有必要将日期指定为本地时区以避免这种情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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