当我将 [NSDate date] 传递给 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 开头?
NSDateComponents
不是 16:00:00
。它正在您当前时区的午夜。但是 NSLog
显示的是等效的 GMT 时间。这就是 +0000
的含义:例如格林威治标准时间 +00:00。
底线,如果你想在你的本地时区看到生成的 NSDate
对象,你应该使用 NSDateFormatter
。
关于ios - 为什么 [日历 dateFromComponents :] always return hour 16 ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34846785/
欢迎光临 OStack程序员社区-中国程序员成长平台 (https://ostack.cn/) | Powered by Discuz! X3.4 |