在 UIDatePicker 中设置默认初始时间 ios

Set default initial time in UIDatePicker ios

在我的 UIDatePicker 中需要将今天显示为默认日期,但将特定时间显示为默认时间。默认情况下它获取当前时间。如何手动设置?

_datePicker = [[UIDatePicker alloc] initWithFrame:CGRectZero];
[_datePicker setDatePickerMode:UIDatePickerModeDate];
_datePicker.datePickerMode = UIDatePickerModeDateAndTime;

您需要的是没有时间的今天日期,然后在上面手动设置时间以获得您需要的日期。日期组件非常适合:

func getTodayDate(at: (hour: Int, minute: Int)) -> Date {
    let dateComponents = Calendar.autoupdatingCurrent.dateComponents([.year, .month, .day], from: Date())
    dateComponents.hour = at.hour
    dateComponents.minute = at.minute
    return Calendar.autoupdatingCurrent.date(from: dateComponents)
}

Objective-C

- (NSDate *)getTodayDateAt:(NSInteger)hour minute:(NSInteger)minute {
    NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];
    NSDateComponents *components = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:[NSDate date]];
    components.hour = hour;
    components.minute = minute;
    return [calendar dateFromComponents:components];
}

现在只需将其设置为您的日期选择器:

_datePicker.date = ...

确保您的日期选择器使用相同的日历。