Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 290
Vork Avatar asked Jun 27 '13 04:06

Vork


3 Answers

setDate: method is used for setting specific date

[yourDatePicker setDate:[NSDate date]];

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

like image 128
Manish Agrawal Avatar answered Nov 14 '22 20:11

Manish Agrawal


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]];
    }
}
like image 39
Ravindhiran Avatar answered Nov 14 '22 20:11

Ravindhiran


In Swift:

yourDatePicker.setDate(date: NSDate, animated: Bool)
like image 45
Jemar Jones Avatar answered Nov 14 '22 22:11

Jemar Jones