Vork
Vork

Reputation: 744

programmatically setting DatePicker time to current time

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.

Upvotes: 6

Views: 20876

Answers (3)

Manish Agrawal
Manish Agrawal

Reputation: 11026

setDate: method is used for setting specific date

[yourDatePicker setDate:[NSDate date]];

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

Upvotes: 16

Jemar Jones
Jemar Jones

Reputation: 1645

In Swift:

yourDatePicker.setDate(date: NSDate, animated: Bool)

Upvotes: 1

Ravindhiran
Ravindhiran

Reputation: 5384

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

Upvotes: 2

Related Questions