Posts Tagged ‘DateTime’

Parsing serialized .NET DateTime to NSDate

Wednesday, February 25th, 2009

In my application I have to parse a serialized .NET DateTime returned from a REST service to a NSDate object. I expected to be able to use the initWithString: constructor of the NSDate class, but this wasn’t the case. The initWithString: constructor expects a string with the following format “2009-02-25 22:00:00 +0100″, yet the serialized .NET DateTime is in the following format “2009-02-25T22:00:00+01:00″. Notice the “T” and the semicolon in the timezone offset.

To solve this difference in format, one could manipulate the actual string to comply to the desired format or one could use the NSDateFormatter class. The latter being the “cleanest” solution.

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"];
NSDate *date = [formatter dateFromString:text];

The used format patterns comply to the Unicode standard UTS #35.