Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
501 views
in Technique[技术] by (71.8m points)

ios - How to parse ISO 8601 using NSDateFormatter with optional milliseconds part

I'm trying to use an NSDateFormatter to parse dates that are in either of these formats

@"2013-02-01T14:21:00"

or

@"2013-02-01T14:21:56.345"

Currently I am using the below method to parse the string and return a date:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"];

[dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];
NSDate *date = [dateFormatter dateFromString:dateToFormat];

This works fine for the first style of date but returns nil for a string that includes the milliseconds part.

I suppose I could test for the existence of the milliseconds and strip them but I was wondering if I could change the date format to treat the .SSS as optional?

Thanks for your help

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As far as I know there is no way to make optional parameters.

The usual solution is to use two formatters, one for each format. To decide which formatter to use, you can either

  1. Count the number of characters in the date string (as suggested in Parsing a RFC 822 date with NSDateFormatter)

  2. Just try both formatters and get the first non-nil result.

Since your date formats are similar, you can go with only one formatter and if the date string is too short, append .000 before using the formatter.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...