Setting UIDatePicker date with NSDateFormatter

后端 未结 1 2018
逝去的感伤
逝去的感伤 2021-01-01 06:09

I am trying to initialize a UIDatePicker with a date that was returned to me from that date picker earlier in my session. This is part of an inventory program that needs to

相关标签:
1条回答
  • 2021-01-01 06:45

    You're missing the Z format specifier in the date format.

    This code:

    NSString *calDate = @"2011-11-11 21:56:38 +0000";
    NSDate *date = [[[NSDate alloc] init] retain];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss Z"];  
    //                                   right here    ^
    
    date = [dateFormatter dateFromString:calDate];
    
    NSLog(@"date:%@", date);
    

    Outputs:

    2012-01-03 20:14:15.258 Craplet[38753:707] date:2011-11-11 21:56:38 +0000
    

    Without the Z:

    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    

    It outputs:

    2012-01-03 20:16:10.456 Craplet[38885:707] date:(null)
    

    If the format cannot be matched to the date string, it returns nil

    0 讨论(0)
提交回复
热议问题