how do I set an existing NSDate's time?

前端 未结 6 437
面向向阳花
面向向阳花 2020-12-08 20:24

how do I set an existing NSDate\'s time?

That is I have a date (say current date/time), but then want to set this to a specific time (e.g. 11.23am) say.

6条回答
  •  隐瞒了意图╮
    2020-12-08 20:31

    iOS 7 Note: I'm putting this in a few of these questions because use of NSUIntegerMax no longer seems to work on iOS7, and using it caused me to chase my tail for about 3 hours. I just discovered that when I use NSUIntegerMax, NSDateComponentsignores set year. So for example this DOES NOT change the year:

    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *comps = [gregorian components:NSUIntegerMax fromDate:date];
    [comps setYear:year];
    return [gregorian dateFromComponents:comps];
    

    Whereas this DOES:

    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSUInteger timeComps = (NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit | NSTimeZoneCalendarUnit);
    NSDateComponents *comps = [gregorian components:timeComps fromDate:date];
    [comps setYear:year];
    return [gregorian dateFromComponents:comps];
    

    It may be an iOS7 bug or it may be that using NSUIntegerMax working was a fluke which no longer works. I will file a bug report and get a definitive answer.

    Regardless, if you want to avoid unexpected consequences specify ALL the components else you might be chasing your tail!

提交回复
热议问题