How can I set only time in NSDate variable?

前端 未结 3 2282
执笔经年
执笔经年 2021-02-14 15:20

I have NSDate variable and would like to change only time (date shouldn\'t be changed). Is it possible ?

Eg: user pick date interval in DatePicker date (If it\'s start d

3条回答
  •  悲哀的现实
    2021-02-14 15:46

    You'll want to use NSDateComponents.

    NSDate *oldDate = datePicker.date; // Or however you get it.
    unsigned unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth |  NSCalendarUnitDay;
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *comps = [calendar components:unitFlags fromDate:oldDate];
    comps.hour   = 23;
    comps.minute = 59;
    comps.second = 59;
    NSDate *newDate = [calendar dateFromComponents:comps];
    

提交回复
热议问题