NSCalendar将firstWeekDay设置为星期一,但结果不同

时间:2015-06-05 02:47:47

标签: ios iphone nsdate nscalendar

我想要获得一个月的开始日期。

- (void)viewDidLoad {
    [super viewDidLoad];
    NSLog(@"begining of month: %@ from today", [self beginningOfMonth:[NSDate date]]);
}

- (NSDate *)beginningOfMonth:(NSDate *)date {
    NSCalendar *calendar = [NSCalendar currentCalendar];
    calendar.locale = [NSLocale currentLocale];
    calendar.timeZone = [NSTimeZone defaultTimeZone];
    calendar.firstWeekday = 2;
    NSDateComponents *componentsCurrentDate = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitWeekday|NSCalendarUnitWeekOfMonth fromDate:date];

    NSDateComponents *componentsNewDate = [NSDateComponents new];

    componentsNewDate.year = componentsCurrentDate.year;
    componentsNewDate.month = componentsCurrentDate.month;
    componentsNewDate.weekOfMonth = 1;
    componentsNewDate.weekday = calendar.firstWeekday;

    return [calendar dateFromComponents:componentsNewDate];
}

但控制台输出为2015-06-05 10:41:54.544 Test[1119:25066] begining of month: 2015-05-31 16:00:00 +0000 我只看了日历,它应该是2015-06-01,但它显示2015-05-31。我确实将第一个星期日定为2天,所以这是星期一。

1 个答案:

答案 0 :(得分:0)

看来你得到了正确的结果。根据Xcode安装的时区,控制台将输出不同的日期。

尝试在NSLog中使用日期格式化程序。

NSDateFormatter *f = [[NSDateFormatter alloc] init];
NSDate *firstMonday = [self beginningOfMonth:[NSDate date];
NSLog(@"First Monday of month: %@", [f stringFromDate:firstMonday]);