【发布时间】:2017-08-03 11:10:25
【问题描述】:
我想从 localDate 获取日期组件,[NSDate localDate] 只需将 GMT 转换为本地时间。
NSDate *localDate=[NSDate localDate];
// localDate:2017-03-13 18:35:35 +0000
NSLog(@"localDate:%@",localDate);
NSInteger dayComponentLocal=[[NSCalendar currentCalendar] component:(NSCalendarUnitDay) fromDate:localDate];
NSLog(@"dayComponentLocal:%ld",(long)dayComponentLocal);
但为什么输出是 14?
有[NSDate localDate]的实现:
NSDate *date=[NSDate date];
NSTimeZone *zone=[NSTimeZone systemTimeZone];
NSInteger interval=[zone secondsFromGMTForDate:date];
NSDate *localDate=[date dateByAddingTimeInterval:interval];
return localDate;
当我想获取当月的第一个工作日时还有另一个错误,代码如下:
NSDate *date=[NSDate localDate];
NSInteger dayComponents=[[NSCalendar currentCalendar] component:(NSCalendarUnitDay) fromDate:date];
NSInteger secondsInADay=24*60*60;
NSDate *firstDay=[date dateByAddingTimeInterval:-((dayComponents-1)*secondsInADay)];
NSInteger weekdayComponent=[[NSCalendar currentCalendar] component:(NSCalendarUnitWeekday) fromDate:firstDay];
NSLog(@"firstDay:%@",firstDay);
NSLog(@"weekday Of firstDay:%ld",weekdayComponent);
由于错误的 dayComponents,我从 'localDate' 中再减去一天并得到错误的 firstDay '2017-02-28 20:09:32 +0000' 而不是正确的答案 '2017-03-01 20: 09:32 +0000'。 2-28 是星期二,但我得到 4,这意味着星期三, 为什么?
【问题讨论】:
标签: ios nsdate nscalendar nsdatecomponents