关于NSDateComponents:为什么我无法获得正确的日期组件?

时间:2017-03-13 12:23:25

标签: ios nsdate nscalendar nsdatecomponents

我想从localDate获取day组件,[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'减去一天并得到错误的第一天'2017-02-28 20:09:32 +0000'而不是正确答案'2017-03-01 20: 09:32 +0000'。 2-28是星期二,但我得到4,这意味着星期三, 为什么呢?

2 个答案:

答案 0 :(得分:0)

您要在localDate中添加GMT的秒数。由于您的时区为正,您需要减去秒(-interval)才能获得UTC。

顺便说一句永远不会使用86400进行日期数学运算。使用NSCalendar

的日期计算方法

例如,您使用

获得当月的第一个工作日
NSCalendar *calendar = [NSCalendar currentCalendar];
// calendar.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
NSDate *startDate;
NSTimeInterval interval;
[calendar rangeOfUnit:NSCalendarUnitMonth startDate:&startDate interval:&interval forDate:[NSDate date]];
NSInteger weekday = [calendar  component:NSCalendarUnitWeekday fromDate:startDate];
NSLog(@"%ld", weekday);

要获取与UTC相关的日期取消注释时区线。

答案 1 :(得分:0)

从拍摄日期组件之前的日期中删除时间组件 试试这段代码

 NSDate *localDate=[NSDate localDate];
    // localDate:2017-03-13 18:35:35 +0000
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"dd-MM-yyyy"];
    NSString *strDate = [dateFormatter stringFromDate: localDate];
    localDate = [dateFormatter dateFromString: strDate];
   NSInteger dayComponentLocal=[[NSCalendar currentCalendar] component:(NSCalendarUnitDay) fromDate:localDate];
   NSLog(@"dayComponentLocal:%ld",(long)dayComponentLocal);

您将获得输出13.这可能是因为时区不同而发生的