UIDatePicker and NSDate

I have an application in which I ask users for their birthday using UIDatePicker, and then saved it in the standard user standards. When the application opens again, I get the date again, and then I want to set the UIDatePicker to this date, but it crashes and does not accept the date. It is stored in the format "June 8, 2009."

How can I do it? Here's how I do it now:

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

My custom 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.

+3
source share
2 answers

From your code, you never set the datePicker date for the date of birth. Try the following:

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

datePicker.date = birthDate;

}

+1
source

objDatePicker - Datepicker,

    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];
+1

Source: https://habr.com/ru/post/1710041/


All Articles