Initialize a NSDate object with a specific time

后端 未结 5 1895
一整个雨季
一整个雨季 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条回答
  •  鱼传尺愫
    2021-02-14 11:34

    Just bringing together some of the Objective C answers, I (now) have this helper function:

    + (NSDate*)dateForTodayAtHour:(NSUInteger)hour andMinutes:(NSUInteger)minutes {
        NSDate* today = [NSDate date];
        NSCalendar* gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
        NSDateComponents* weekdayComponents = [gregorian components:(NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear) fromDate:today];
        [weekdayComponents setHour:hour];
        [weekdayComponents setMinute:minutes];
        [weekdayComponents setSecond:0];
        NSDate* result = [gregorian dateFromComponents:weekdayComponents];
        return result;
    }
    

提交回复
热议问题