schaz
schaz

Reputation: 895

Setting UIDatePicker date with NSDateFormatter

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 get the date that in inventory item was last calibrated.

Using this code I receive a date/time string:

NSDate *choice = [pickedDate date];
calDate = [[NSString alloc] initWithFormat:@"%@", choice];

I end up with the following string in calDate: 2011-11-11 21:56:38 +0000

I am trying to set my date picker with the following code:

NSDate *date = [[[NSDate alloc] init] retain];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSLog(@"cal date = %.@.",drawingInfo.drawingDate);
if([calDate length] != 0) {
    date = [dateFormatter dateFromString:calDate];

    if(date != nil) {
            [pickedDate setDate:date animated:NO];
    }
}

The NSLog verifies that the string is still in tact. If I put a breakpoint on the if(date != nil) it shows me that date = nil.

Thanks in advance.

Upvotes: 3

Views: 12580

Answers (1)

bryanmac
bryanmac

Reputation: 39296

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

Upvotes: 7

Related Questions