how do I set an existing NSDate's time?

前端 未结 6 433
面向向阳花
面向向阳花 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:52

    Apply this to set the Time from an another date to an existing Date

    NSDate *today = [NSDate date]; // from which i need only "Year" "Month" "Date"
    
    NSCalendar *calendar = [NSCalendar currentCalendar]
    NSDateComponents *dateComponents = [calendar components:( NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit ) fromDate:today];
    
    NSDate *timeDate = datePicker.date; // from which i need only "Hours" "Minutes" and "Seconds"
    
    NSDateComponents *timeComponents = [calendar components:( NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit ) fromDate:timeDate];
    
                [dateComponents setHour:[timeComponents hour]];
                [dateComponents setMinute:[timeComponents minute]];
                [dateComponents setSecond:[timeComponents second]];
    
    NSDate *newDate = [calendar dateFromComponents:dateComponents]; // New Date with My "Year" "Month" "Date" "Hours" "Minutes" and "Seconds" 
    
                NSLog(@"New Date: %@",newDate);
    

提交回复
热议问题