NSDate from NSString - dateFromString returns nil

Go To StackoverFlow.com

0

I want to get a NSDate object from a string of date, but it returns nil. What am I doing wrong? Thanks!

NSString *dateString = @"2012-04-05T13:27:32.369Z";

NSDateFormatter* df = [[NSDateFormatter alloc]init];
[df setDateFormat:@"YYYY-MM-dd'T'HH:mm:ss.SSSZ"];
NSDate* date = [df dateFromString:dateString];
NSLog(@"1%@",date);
[df release];
2012-04-05 17:34
by nurxyz
Put the Z in single quotes - Hot Licks 2012-04-05 17:48
I agree with Aadhira - Nilesh 2012-04-05 18:06


4

The "Z" must be quoted:

NSDateFormatter* df = [[NSDateFormatter alloc]init];
NSString *dateString = @"2012-04-05T13:27:32.369Z";
[df setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"];
NSDate* date = [df dateFromString:dateString];
NSLog(@"1: %@",date);

NSString *newDateString = [df stringFromDate:date];
NSLog(@"2: %@",newDateString);

NSLog output:

1: 2012-04-05 17:27:32 +0000
2: 2012-04-05T13:27:32.369

Keep in mind that NSLog uses the NSDate default formatter with the current timezone.

See: Date_Field_Symbol_Table

2012-04-05 17:54
by zaph


1

It should be yyyy for years

[df setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"];
2012-04-05 17:37
by Ilanchezhian
"yyyy-MM-dd'T'HH:mm:ss.SSSZ" still returns null - zaph 2012-04-05 17:50


0

Use NSDateFormatter to get a NSDate then use - (NSTimeInterval)timeIntervalSince1970 to get the seconds since 1970.

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];
[formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"];
NSDate *date = [formatter dateFromString:@"2012-04-05T13:27:32.369Z"];
NSLog(@"Date: %@", date);
NSLog(@"1970: %f", [date timeIntervalSince1970]);
NSLog(@"sDate: %@", [formatter stringFromDate:date]);
[formatter release];

Hope it helps.

2012-04-05 18:05
by Nilesh
Ads