fadd fadd - 4 months ago 30
iOS Question

Set UIDatepicker programatically

I have a datepicker and 2 buttons. And i want to set the datepicker value programatically when i click the button. Like when i press the first button the datepicker value becomes today's date and 00:00:00: time and when i press the second button the datepicker value becomes today's date and 23:59:59 time.

How to do that?

iOS iOS
Answer

Simple task, assuming that you already added two functions beging invoked on button pressing you need something like this:

-(IBAction)beginPressed:(id)sender
{
  NSDate * now = [[NSDate alloc] init];
  NSCalendar *cal = [NSCalendar currentCalendar];
  NSDateComponents * comps = [cal components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:now];
  [comps setHour:0];
  [comps setMinute:0];
  [comps setSecond:0];
  NSDate * date = [cal dateFromComponents:comps];
  [self.datePicker setDate:date animated:TRUE];

}
-(IBAction)endPressed:(id)sender
{
  NSDate * now = [[NSDate alloc] init];
  NSCalendar *cal = [NSCalendar currentCalendar];
  NSDateComponents * comps = [cal components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:now];
  [comps setHour:23];
  [comps setMinute:59];
  [comps setSecond:59];
  NSDate * date = [cal dateFromComponents:comps];
  [self.datePicker setDate:date animated:TRUE];
}

I think the part with setting the components wasn't clear to you, check the API of the above classes and you will find more.

Edit: I changed the calendar to the current default calendar and initialized the calendar with now.

Comments