简体   繁体   中英

NSDateFormatter format for a specific string

If 'string' looks something like this '2014-03-04T15:06:54.000Z', what should this line look like? myDate is getting set as nil with the below format.

[formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'Z'"];

+ (NSDate *)convertStringtoDate:(NSString *)string {

    NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'Z'"];

    NSDate *myDate = [formatter dateFromString:string];

    return myDate;
}

Furthermore, I'd appreciate a good resource for learning how to look this up on my own. The date formatting concept is a tough one for my tiny cerebral.

Try using "SSS" as format specifier to catch milliseconds, even if you don't use them. Your format string would then become:

[formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"];

See here for formatting reference: http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_Patterns .

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