数值:星期几

时间:2013-10-10 13:10:14

标签: ios nsdate nsdateformatter

我根据星期几改变文本值,我能够使用字符串值来实现这一点,但我希望能够在数字值上实现 - 删除不同语言的问题。例如,如果今天是星期一做...但我想如果今天是第1天然后做。我已经尝试了下面的代码,但它给了我一个0的数值;

    NSDateFormatter *dayofweekformatter = [[NSDateFormatter alloc] init];
[dayofweekformatter setDateFormat:@"E"];

NSString *DayOfWeek = [dayofweekformatter stringFromDate:[NSDate date]];
NSInteger weekDay = [DayOfWeek integerValue];
NSLog(@"The day of the week is: %d", weekDay);

是否可以这样做?

2 个答案:

答案 0 :(得分:0)

根据this链接,“E”本身将以星期几的形式提供文本格式,即:“星期一”/“星期二”等。

如果您希望将星期几作为整数,则应使用小写“e”或“c”。

另一种实现方式是使用NSCalendarNSDateComponents来确定星期几,因为这更有可能根据用户首选日历考虑不同设备的不同设置。< / p>

NSDate *date = [NSDate date];

NSCalendar *calendar = [NSCalendar currentCalendar];

NSDateComponents *dateComponents = [calendar components:NSCalendarUnitWeekday fromDate:date];

NSLog(@"day of the week: %i", [dateComponents weekday]);

答案 1 :(得分:0)

以下是Apple论坛上提出的解决方案https://discussions.apple.com/thread/1700102?start=0&tstart=0(我不是作者)

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

NSDateComponents *weekdayComponents =[gregorian components:NSWeekdayCalendarUnit fromDate:dateOfInterest];

NSInteger weekday = [weekdayComponents weekday];
// weekday 1 = Sunday for Gregorian calendar

[gregorian release];
相关问题