当我将[NSDate日期]传递给NSDateComponents,然后在工作日修改后传回,我总是得到16:00:00。为什么?
以下代码:
{
NSCalendar *calendar = [[NSCalendar alloc]initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDate *now = [NSDate date];
NSLog(@"now = %@",now);
NSDateComponents *firstDayOfWeek = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitWeekday fromDate:now];
firstDayOfWeek.weekday = 1; // Monday as first day of week
NSDate *firstDayOfWeekDate = [calendar dateFromComponents:firstDayOfWeek];
NSLog(@"first day = %@", firstDayOfWeekDate);
}
{
NSCalendar *calendar = [[NSCalendar alloc]initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDate *now = [NSDate date];
NSLog(@"now = %@",now);
NSDateComponents *firstDayOfWeek = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitWeekday | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond fromDate:now];
firstDayOfWeek.weekday = 1; // Monday as first day of week
firstDayOfWeek.hour = 1;
firstDayOfWeek.minute = 1;
firstDayOfWeek.second = 1;
NSDate *firstDayOfWeekDate = [calendar dateFromComponents:firstDayOfWeek];
NSLog(@"first day = %@", firstDayOfWeekDate);
}
输出是:
now = 2016-01-18 03:14:08 +0000
first day = 2016-01-17 16:00:00 +0000
now = 2016-01-18 03:14:08 +0000
first day = 2016-01-17 17:01:01 +0000
为什么小时从16开始?
答案 0 :(得分:1)
这是由于时区。
尝试在使用NSDateFormatter
输出日期之前添加NSLog
,例如
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setLocale:[NSLocale currentLocale]];
[dateFormatter setDateStyle:NSDateFormatterShortStyle];
[dateFormatter setTimeStyle:NSDateFormatterLongStyle];
NSString *dateDisplay = [dateFormatter stringFromDate:firstDayOfWeekDate];
NSLog(@"first day = %@",dateDisplay);
您可以参考this article了解更多示例。
答案 1 :(得分:1)
NSDateComponents
没有将其16:00:00
。它正在你当前时区的午夜。但NSLog
向您显示相当的GMT时间。这就是+0000
的含义:例如GMT +00:00。
底线,如果您想在当地时区看到生成的NSDate
对象,则应使用NSDateFormatter
。