get current date from [NSDate date] but set the time to 10:00 am

前端 未结 5 923
小鲜肉
小鲜肉 2020-12-01 02:17

How can I reset the current date retrieved from [NSDate date] but then change the time to 10:00 in the morning.

5条回答
  •  既然无缘
    2020-12-01 03:05

    As with all date manipulation you have to use NSDateComponents and NSCalendar

    NSDate *now = [NSDate date];
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier: NSCalendarIdentifierGregorian];
    NSDateComponents *components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:now];
    [components setHour:10];
    NSDate *today10am = [calendar dateFromComponents:components];
    

    in iOS8 Apple introduced a convenience method that saves a few lines of code:

    NSDate *d = [calendar dateBySettingHour:10 minute:0 second:0 ofDate:[NSDate date] options:0];
    

    Swift:

    let calendar: NSCalendar! = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
    let now: NSDate! = NSDate()
    
    let date10h = calendar.dateBySettingHour(10, minute: 0, second: 0, ofDate: now, options: NSCalendarOptions.MatchFirst)!
    

提交回复
热议问题