UIDatePicker and NSDate

喜你入骨 提交于 2019-12-07 13:20:19

问题


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


来源:https://stackoverflow.com/questions/967757/uidatepicker-and-nsdate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!