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];
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.
It should be yyyy
for years
[df setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"];
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.