UIDatePicker and NSDate

2019-05-11 19:01发布

问题:

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.

回答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;

}



回答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];