fadd
fadd

Reputation: 584

Set UIDatepicker programmatically

I have a datepicker and 2 buttons. And I want to set the datepicker value programmatically 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?

Upvotes: 4

Views: 12731

Answers (3)

jxmorris12
jxmorris12

Reputation: 1372

For those wondering how to do this in Swift:

let now = NSDate()
let cal = NSCalendar.currentCalendar()
let comp = cal.components([.Year, .Month, .Day], fromDate: now)
comp.hour = 0 // or whatever you need
comp.minute = 0
let date = cal.dateFromComponents(comp)!
picker.setDate(date, animated: true)

Upvotes: 2

Dnyaneshwar
Dnyaneshwar

Reputation: 21

NSDateFormatter *dateFormat;
  dateFormat = [[NSDateFormatter alloc] init];
 [dateFormat setDateFormat:@"h:mm a"];
  NSDate *exampleDateFromString =[dateFormat dateFromString:@"8:48 AM"]; 
  date-picker.minimumDate=exampleDateFromString;
 [date-picker setDate:exampleDateFromString];

Upvotes: 2

iOS
iOS

Reputation: 813

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.

Upvotes: 12

Related Questions