返回明天的名字

时间:2013-06-16 21:44:25

标签: objective-c nsdate nsdateformatter

我想返回明天的工作日名称(即如果今天是星期天,我想要星期一)。这是我的代码,它产生了今天的工作日名称。

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"EEEE"];
weekDay =  [formatter stringFromDate:[NSDate date]];

而不是搞乱NSCalendar,这样做的简洁方法是什么(遵循我在这里的代码)?

谢谢。

3 个答案:

答案 0 :(得分:3)

用户的语言识别:

NSDateFormatter * df = [[NSDateFormatter alloc] init];
NSArray *weekdays = [df weekdaySymbols];

NSDateComponents *c = [[NSDateComponents alloc] init];
c.day = 1;
NSDate *tomorrow = [[NSCalendar currentCalendar] dateByAddingComponents:c
                                                                 toDate:[NSDate date]
                                                                options:0];
c = [[NSCalendar currentCalendar] components:NSWeekdayCalendarUnit
                                    fromDate:tomorrow];

NSString *tomorrowname = weekdays[c.weekday-1];// the value of c.weekday may 
                                               // range from 1 (sunday) to 7 (saturday)    
NSLog(@"%@", tomorrowname);

如果您需要使用某种语言的名称,请添加

[df setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];

创建日期格式化程序后。

答案 1 :(得分:1)

你为什么害怕“搞乱”NSCalendar?要使用NSDateComponents方法,您实际上必须使用NSCalendar。这是我解决问题的方法。

// Get the current weekday
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *weekdayComponents = [calendar components:NSWeekdayCalendarUnit fromDate:[NSDate date]];
// !! Sunday = 1
NSInteger weekday = [weekdayComponents weekday];

现在,您可以使用NSDateFormatter方法 - (NSArray *) weekdaySymbols ,其中包含从星期日开始在索引0处的工作日。作为[weekdayComponents weekday]返回的整数星期六从0开始,我们必须增加工作日存储的值:

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
// !! Sunday = 0
NSUInteger symbolIndex = (weekday < 7) ? weekday : 0;
NSString *weekdaySymbol = [[formatter weekdaySymbols] objectAtIndex:(NSUInteger)symbolIndex];

我希望尽管在某种程度上使用NSCalendar会有所帮助。

编辑: glektrik的解决方案非常直接。但请注意 - dateByAddingTimeInterval:的NSDate类引用中的以下语句。

  

返回值   一个新的NSDate对象,设置为相对于接收器的秒秒。返回的日期可能与接收者的表示不同。

答案 2 :(得分:1)

感谢您的评论,Abizern。这是我做的:

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"EEEE"];
    weekDay = [formatter stringFromDate:[NSDate date]];

    NSDateComponents *tomorrowComponents = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:[NSDate date]];

    NSDate *compDate = [[NSCalendar currentCalendar] dateFromComponents:tomorrowComponents];

    NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
    offsetComponents.day = 1;
    NSDate *tomorrow = [[NSCalendar currentCalendar] dateByAddingComponents:offsetComponents toDate:compDate options:0];

    nextWeekDay = [formatter stringFromDate:tomorrow];

两个NSString对象(weekDay和nextWeekDay)现在存储今天和明天(当前星期日和星期一)的星期几。 这很好用,但我想知道是否有更简单的方法。 Objective-C日期非常繁琐:(

再次感谢。