Hunter Mitchell
Hunter Mitchell

Reputation: 7293

NSDateFormatter Trouble?

I am trying to parse an RSS feed, but the date is hard to parse. The date string is: publishedDate = "2013-01-08T20:09:02.000Z"

Here is my code:

NSDateFormatter *utc = [[NSDateFormatter alloc] init];
[utc setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];
[utc setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'Z'"];
NSDate *dtUTC = [utc dateFromString: publishedDate];

NSDateFormatter *dfLocal = [[NSDateFormatter alloc] init];
[dfLocal setDateFormat:@"yyyy-MM-dd"];
[dfLocal setTimeZone:[NSTimeZone localTimeZone]];

NSString *time =[dfLocal stringFromDate:dtUTC];
NSLog(@"original UTC %@  now local: %@", dtUTC, time);

Why is date returning nil? Also, i am trying to convert UTC time to CST Time.

Upvotes: 2

Views: 1260

Answers (3)

zaph
zaph

Reputation: 112873

For stime that includes miliseconds use "S".

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

NSString *publishedDate = @"2013-01-08T20:09:02.000Z";
NSDateFormatter *utc = [[NSDateFormatter alloc] init];
[utc setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];
[utc setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'.'SSS'Z'"];
NSDate *dtUTC = [utc dateFromString: publishedDate];
NSLog(@"dtUTC: %@", dtUTC);

NSLog output:
dtUTC: 2013-01-08 20:09:02 +0000

SDateFormatter *dfLocal = [[NSDateFormatter alloc] init];
[dfLocal setDateFormat:@"yyyy-MM-dd"];
[dfLocal setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];

NSString *time =[dfLocal stringFromDate:dtUTC];
NSLog(@"original UTC %@  now local: %@", dtUTC, time);

NSLog output:
original UTC 2013-02-08 20:09:02 +0000 now local: 2013-02-08

Upvotes: 1

wigging
wigging

Reputation: 9190

Just change your time zone name to CST and change the setDateFormat as follows:

NSDateFormatter *cst = [[NSDateFormatter alloc] init];
    [cst setTimeZone:[NSTimeZone timeZoneWithName:@"CST"]];
    [cst setDateFormat:@"yyyy-mm-dd'T'HH:mm:ss.'000Z'"];
    NSDate *theCST = [cst dateFromString:publishedDate];
    NSLog(@"theCST is %@", theCST);

Upvotes: 1

msk
msk

Reputation: 8895

Use

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

Upvotes: 2

Related Questions