0

In my UIDatePicker need to display today as a default date but specific time as a default time. Bydefault it gets current time. How to set it manually?

_datePicker = [[UIDatePicker alloc] initWithFrame:CGRectZero];
[_datePicker setDatePickerMode:UIDatePickerModeDate];
_datePicker.datePickerMode = UIDatePickerModeDateAndTime;
isuru
  • 3,385
  • 4
  • 27
  • 62
  • 2
    `[_datePicker setDate:theDateOfTodayWithTheDefaultTimeYourWant]`? – Larme Apr 19 '18 at 08:56
  • @Larme [NSDate date] gives current time as well. So how to give date and time separately. – isuru Apr 19 '18 at 08:59
  • 1
    Then your question is about: How do I create a date at specific hour and minutes? Then it's there: https://stackoverflow.com/questions/7288671/how-to-set-time-on-nsdate – Larme Apr 19 '18 at 09:01

1 Answers1

3

What you need is a today date without time and then set the time manually on it to get a date you need. Date components are perfect for that:

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];
}

Now just set it to your date picker:

_datePicker.date = ...

Make sure your date picker uses the same calendar though.

Matic Oblak
  • 16,318
  • 3
  • 24
  • 43