programmatically setting DatePicker time to current time

20,520

Solution 1

setDate: method is used for setting specific date

[yourDatePicker setDate:[NSDate date]];

It will set picker date and time to current date and time.

Solution 2

Try this,

ViewController.h

@interface ViewController : UIViewController
{
  IBOutlet UISwitch *onOffSwitch;
  UIDatePicker *myPicker;
}
-(IBAction)onOffSwitch:(id)sender;

@end

ViewController.m

  - (void)viewDidLoad
    {
    [super viewDidLoad];
    CGRect pickerFrame = CGRectMake(0,250,0,0);
    myPicker = [[UIDatePicker alloc] initWithFrame:pickerFrame];
    [self.view addSubview:myPicker];
    [myPicker release];
    }

    -(IBAction)onOffSwitch:(id)sender{

    if(onOffSwitch.on) {

        NSString *dateStr = @"Tue, 25 May 2010 12:53:58 +0000";
        // Convert string to date object
        NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
        [dateFormat setDateFormat:@"EE, d LLLL yyyy HH:mm:ss Z"];
        NSDate *date = [dateFormat dateFromString:dateStr];
        [myPicker setDate:date];
    }
    else 
    {
        [myPicker setDate:[NSDate date]];
    }
}

Solution 3

In Swift:

yourDatePicker.setDate(date: NSDate, animated: Bool)
Share:
20,520
Vork
Author by

Vork

Updated on January 22, 2020

Comments

  • Vork
    Vork over 4 years

    I am using an alarm functionality in my iphone app. Here when I put the state of uiswitch to "ON" and select a particular time from DatePicker, till user change the state of uiswitch to off, datepicker should show the selected time, and when the state is changed to off, date picker should show the current time, not previously selected one. I cannot find any option to set datepickers time value to current time programmatically.