NSDateComponents返回nil

Ove*_*esh 17 objective-c nsdate ios

我正在尝试将一个NSDate对象的小时,分​​钟和秒初始化为0.我正在使用下面的代码来获取它,但由于某种原因,我从[NSDateComponents date]得到nil.我的代码出了什么问题?

NSCalendar *gregorian = [[[NSCalendar alloc]
                          initWithCalendarIdentifier:NSGregorianCalendar] autorelease];

NSDate *now = [[[NSDate alloc] init] autorelease];
NSDateComponents *nowDc = [gregorian components:(NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit) 
        fromDate:now];
// this returns nil!
NSDate *todayStart = [nowDc date];
Run Code Online (Sandbox Code Playgroud)

Mat*_*uch 34

从日历实例获取组件时,未设置NSDateComponents实例的日历.

但是您必须先设置日历才能使用[components date],因为没有日历就没有日期.

所以尝试添加 [nowDc setCalendar:gregorian];

  • 它没有明确说明.但是在日期编程指南中暗示了这一点.NSDate(作为时间点)和日月份之间的区别非常重要.由于同样的原因,没有[NSDate dateWithYear:month:date]方法.没有NSCalendar日,月份和年份都没有意义. (3认同)