UIDatePicker and NSDate

10,354

Solution 1

From your code, you never set the datePicker's date to be birthdate. Try this:

- (void)viewWillAppear:(BOOL)animated {
NSDate *birthDate = [Preferences getBirthDate];
if (birthDate == nil) {
    birthDate = [NSDate date];
}

datePicker.date = birthDate;

}

Solution 2

Here objDatePicker is Datepicker object,

    NSDateFormatter *formate = [[NSDateFormatter alloc] init];  
    [formate setDateFormat:@"dd-MM-yyyy  HH:mm:ss"];
    NSTimeZone *zone=[NSTimeZone defaultTimeZone];
    [formate setTimeZone:zone];
    NSDate *date = [formate dateFromString:timeTextField.text];  
    NSLog(@"Output :%@",date);
    [objDatePicker setDate:date];
Share:
10,354
Xcoder
Author by

Xcoder

Updated on June 06, 2022

Comments

  • Xcoder
    Xcoder about 2 years

    I have an app where I ask for the users birthday with a UIDatePicker then store it in standard user defaults. When the app is opened again I get the date again and then want to set the UIDatePicker to that date but it's crashing and not accepting the date. It's being stored in the format "June 8, 2009."

    How do I need to do this? This is the way I'm trying it now:

    - (void)viewWillAppear:(BOOL)animated {
        birthDate = [Preferences getBirthDate];
        if (birthDate == nil) {
            [datePicker setDate:[NSDate date] animated:NO];
        }       
    }
    

    My user pref methods look like this in their class:

    + (NSDate *)getBirthDate {
        // Geting via user defaults....
        if ([[NSUserDefaults standardUserDefaults] objectForKey:@"DOB"])
            return [[NSUserDefaults standardUserDefaults] objectForKey:@"DOB"];
        else {
            return nil;
        }
    }
    
    + (BOOL)setBirthDate:(NSDate *)bDate {
        //Setting via user defaults
        [[NSUserDefaults standardUserDefaults] setObject:bDate forKey:@"DOB"];
        return [[NSUserDefaults standardUserDefaults] synchronize];
    }
    

    Thanks in advance.

  • Xcoder
    Xcoder about 15 years
    Thanks! I was trying to use [datePicker setDate:birthDate] to set the date. What does that method do if it doesn't set the date to what you want?
  • KRISH SHAH
    KRISH SHAH about 15 years
    [datePicker setDate:birthDate] is the same thing as datePicker.date=birthDate. The main difference is that if birthDate is not equal to nil in your code, the datePicker's date does not get set.
  • Xcoder
    Xcoder about 15 years
    Yes, I know. I commented it out because [datePicker setDate:birthDate] was crashing it. However, for some reason datePicker.date did not. Very strange.