Initialize a NSDate object with a specific time

后端 未结 5 1883
一整个雨季
一整个雨季 2021-02-14 11:17

I have time in string format for example 2:00. I want to initialize it to NSDate with present date. I tried doin

5条回答
  •  闹比i
    闹比i (楼主)
    2021-02-14 11:36

    To initialize an NSDate with the present date at 2, you'll have to split an NSDate with components year, month, and day, e.g.

    NSDate *today = [NSDate date];
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *weekdayComponents = [gregorian
                                           components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit)
                                           fromDate:today];
    

    Set the hours to 2

    weekdayComponents.hour = 2;
    

    And then create a new NSDate by those components

    NSDate *todayAt2 = [gregorian dateFromComponents:weekdayComponents];
    

提交回复
热议问题