简体   繁体   中英

Problem formatting date using NSDateFormatter

I have the following date:

2011-09-09T18:01:47Z

I want it to appear as

"9/9/11 at 1:47PM" whatever the correct time is

This code returns a null string:

NSLog(@"TIME: %@",[message valueForKey:@"created_at"]);
    NSString* time = [message valueForKey:@"created_at"];
    NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"MM-dd-yy at HH:mm:ss"];
    NSDate* newTime = [dateFormatter dateFromString:time];
    [dateFormatter setDateFormat:@"MM-dd-yy at HH:mm:ss"];
    NSString* finalTime = [dateFormatter stringFromDate:newTime];

Your formatting is the same for both and they have little to no relation to your input and your output. Refer to the Unicode Data Format Patterns whenever you have issues.

NSString *datein = @"2011-09-09T18:01:47Z";

NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
//The Z at the end of your string represents Zulu which is UTC
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'Z'"];
NSDate* newTime = [dateFormatter dateFromString:datein];

//Add the following line to display the time in the local time zone
[dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
[dateFormatter setDateFormat:@"M/d/yy 'at' h:mma"];
NSString* finalTime = [dateFormatter stringFromDate:newTime];
NSLog(@"%@", finalTime);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM