9

为了获得我使用的星期几:

NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
NSArray *weekdays = [dateFormatter shortWeekdaySymbols];

Weekdays 给了我一个包含日期名称的数组,但它从星期日开始。由于某些原因,我希望这个数组在周一或周日开始,具体取决于设备的本地化设置。

有没有办法做到这一点?

4

5 回答 5

15

您可以从具有当前语言环境的对象的-firstWeekday方法中获取当前语言环境的第一个工作日的从 1 开始的索引。NSCalendar然后您可以相应地修改您的周名称数组:

// get week day names array
NSArray *weekdays = self.shortWeekdaySymbols;

// adjust array depending on which weekday should be first
NSUInteger firstWeekdayIndex = [NSCalendar currentCalendar].firstWeekday - 1;
if (firstWeekdayIndex) {

    NSRange firstRange = NSMakeRange(firstWeekdayIndex, weekdays.count - firstWeekdayIndex);
    NSRange lastRange = NSMakeRange(0, firstWeekdayIndex);

    NSArray *firstArray = [weekdays subarrayWithRange:firstRange];
    NSArray *lastArray  = [weekdays subarrayWithRange:lastRange];

    weekdays = [firstArray arrayByAddingObjectsFromArray:lastArray];
}

NSLog(@"%@", weekdays);

我没有 iPhone SDK,但 AFAIK 这些 API 应该都在那里可用,并且行为方式与 OS X 上的相同。

于 2010-09-02T13:33:50.073 回答
1

使用以下方法在 Swift 中实现了类似于 hasseg 的结果:

    var symbols = dateFormatter.shortWeekdaySymbols as! [String]
    let firstDayIndex = calendar.firstWeekday - 1

    if firstDayIndex > 0 {
        var sub = symbols[0..<firstDayIndex]
        symbols.removeRange(Range<Int>(start:0, end:firstDayIndex))
        symbols += sub
    }
于 2015-03-13T13:05:33.623 回答
1

您需要使用NSCalender以编程方式更改一周的开始日期。

NSCalendar *_calendar;
_calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
_calendar.timeZone = [NSTimeZone localTimeZone];
[_calendar setFirstWeekday:2];// Sunday == 1, Saturday == 7
_calendar.locale = [NSLocale currentLocale];

    NSDateComponents *dateComponent = [_calendar components:(NSCalendarUnitWeekOfYear | NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear) fromDate:[NSDate date]];
    NSDate *now = [NSDate date];
    NSDateComponents *comp = [_calendar components:NSCalendarUnitYear fromDate:now];
    [comp setWeekOfMonth:dateComponent.weekOfYear];  //Week number.
    [comp setWeekday:2];

    NSDate * weekstartPrev = [_calendar dateFromComponents:comp];
于 2017-02-08T05:44:13.810 回答
1

像 myexec 解决方案,但更通用且同样简洁

let numDays = Calendar.current.weekdaySymbols.count
let first = Calendar.current.firstWeekday
let end = first + numDays - 1

let days = (first...end).map {Calendar.current.weekdaySymbols[$0 % numDays]}
于 2017-02-07T23:04:38.210 回答
0
for i in 0...6 {
    let day = Calendar.current.weekdaySymbols[(i + Calendar.current.firstWeekday - 1) % 7]
    print(day)
}
于 2016-09-19T10:33:29.640 回答