100
votes

I'm required to parse strings in a format that includes milliseconds. What format string do I use to get the right date value?

For example, suppose I have a string with the following value: "2011-06-23T13:13:00.000"

What format string do I pass to my NSDateFormatter in the following code?

NSString *dateValue = @"2011-06-23T13:13:00.000";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
NSString *formatString = @"yyyy-MM-dd'T'HH:mm:ss.???";
[formatter setDateFormat:formatString];
NSDate *date = [formatter dateFromString:dateValue];

What do I use in place of ??? in the code above?

4

4 Answers

212
votes

It's SSS, per the Unicode Locale Data Markup Language spec.

"yyyy-MM-dd'T'HH:mm:ss.SSS"

More generally, use any number of upper-case S characters to get that many decimal places in the fractions-of-a-second component. (So ss.S will show the time to the nearest tenth of a second, for example.)

7
votes

The Date Format Patterns guide suggests that "S" is the format specifier for fractions of seconds.

5
votes

You need to pass same number of 'S' at the end for example My Date was '2015-11-17T03:36:45.041503Z' the i used 'yyyy-MM-dd'T'HH:mm:ss.SSSSSSz' formatter, I mean see the number of 'S' is 6 as 6 digit coming in date.

-1
votes

use SSS for three decimal places of a second

"yyyy-MM-dd'T'HH:mm:ss.SSS"