如何使用NSDateFormatter获取星期几并在iOS中显示使用NSLog?

时间:2012-03-26 18:47:55

标签: objective-c cocoa

  

可能重复:
  how do I get the day of the week using NSDate and show using NSLog in iOS?

使用以下代码。

NSDateFormatter* day = [[NSDateFormatter alloc] init];  
[day setDateFormat: @"EEEE"];  
NSLog(@"the day is: %@", [day stringFromDate:[NSDate date]]);

如何将此值放入变量?
我想使用if,例如:

if (day == "monday")  
{  
  ...    
}

1 个答案:

答案 0 :(得分:14)

这是你如何做到的。始终设置您想要获取日期名称的语言环境,因为默认名称可能不是英语。

NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setFormatterBehavior:NSDateFormatterBehavior10_4];
dateFormatter.locale = [[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"] autorelease];
[dateFormatter setDateFormat:@"EEEE"];
NSString *dayName = [dateFormatter stringFromDate:[NSDate date]];
if ([dayName isEqualToString:@"Monday"]) {
}