1

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

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

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

谢谢你。

4

3 回答 3

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"]];

在创建日期格式化程序之后。

于 2013-06-16T23:18:59.950 回答
1

谢谢你的评论,阿比伦。这是我所做的:

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 日期非常麻烦:(

再次感谢。

于 2013-06-16T23:18:25.270 回答
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 开始,我们不必增加存储在 weekday 中的值:

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 对象,相对于接收者设置为 seconds 秒。返回的日期可能具有与接收者不同的表示。

于 2013-06-16T22:49:24.583 回答