tags:

views:

45

answers:

3

I want to convert the following date: 2010-02-01T13:58:58.513Z

Which is stored in a NSStringto and NSDate.

The following however just shows "NULL" in the debugger

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];

[formatter setDateFormat:@"YYYY-MM-DDTHH:MM:SS.tttZ"];

NSLog(@"Output: %@", [formatter dateFromString:@"2010-02-01T13:58:58.513Z"]);

[formatter release];

Ideas?

A: 

Best Guess: Your date format has a space in it. Try this:

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];

[formatter setDateFormat:@"YYYY-MM-DD'T'HH:mm:SS.SSS'Z'"];

NSDate *date = [formatter dateFromString:@"2010-02-01T13:58:58.513Z"];

NSLog(@"Output: %@", [date description]);

[formatter release];
Stephen Furlani
That prints null too.
Filip Ekberg
Sorry. Try my fix, it prints for me.
Stephen Furlani
It does print something, but the wrong date. Prints 2010-01-01
Filip Ekberg
A: 

There are several problem in your format :

  • MM is for month while mm is for minutes
  • SS does not exists, use ss instead
  • same for ttt, use AAA
  • there is space between in your format string that looks like a typo but will cause failure

what time zone does Z code stand for at the end of your time (2010-02-01T13:58:58.513Z)

try

[formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss.AAA'Z'"];

This will create a GMT Time because it recognize the Z ate the end a as simple letter and not as time zone.

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

VdesmedT
Still gives me: "Output: (null)".
Filip Ekberg
AAA is for milliseconds in day, while SSS is for fractional seconds, which I think is what he means.
Yannick Compernol
+1  A: 

You have to escape the "T" in the format string with single quotes.

[formatter setDateFormat:@"YYYY-MM-DD'T'HH:MM:SS.tttZ"];

--

Edit: your formatters aren't completely correct either. ttt for instance is not a valid formatter according to the documentation. Official documentation

If I do this I can get it to work, but that doesn't solve the Z problem:

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"YYYY-MM-DD'T'HH:mm:ss.SSS"];
NSLog(@"Output: %@", [formatter dateFromString:@"2010-02-01T13:58:58.513"]);
[formatter release];

--

Edit 2: Bingo, found the correct formatter.

[formatter setDateFormat:@"YYYY-MM-dd'T'HH:mm:ss.SSS'Z'"];
Yannick Compernol
How about the Z ? It's still null with that.
Filip Ekberg
Working on it, one moment, the Z is not the only problem.
Yannick Compernol
Well that displays something else than null. But it gives me the wrong date: 2010-01-01.
Filip Ekberg
DD is for day of year, should be dd. Fixed it in the answer.
Yannick Compernol
Works like a charm! :) thanks
Filip Ekberg
Be careful that your Z timezone is not interpreted
VdesmedT