tranvutuan
tranvutuan

Reputation: 6109

parsing date from string, nsdate, objective c

Below is a string represented a date

NSString *dateStr = @"2011-07-06";

And when I am trying to convert it to NSDate by doing :

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

    [format setDateFormat:@"yyyy-MM-dd"];
    NSDate      *tmp                =   [format dateFromString:dateStr];
    NSLog(@"tmp  is %@",[tmp description]);

What I am getting from the console is

tmp  is 2011-07-06 04:00:00 +0000

I dont understand why I am getting extra info :04:00:00 +0000 for the result

Please help if you experienced it before

Upvotes: 0

Views: 3573

Answers (2)

vikingosegundo
vikingosegundo

Reputation: 52237

Your code

NSString *dateStr = @"2011-07-06";
NSDateFormatter *format         =   [[NSDateFormatter alloc] init];

[format setDateFormat:@"yyyy-MM-dd"];
NSDate      *tmp                =   [format dateFromString:dateStr]

will result in a NSDate object, that represents your local time at 0:00 — the beginning of the day.

but if you print a plain date object, it will result in a string that represents the time in GMT timezone, as internally all dates are normalized to that timezone.

As your string is 4 hours ahead, we can tell, that you most likely are in East Europe, maybe Moscow.

So if you want to see the string in your timezone, you need to use a NSDateFormatter to create it from the date object.

NSLog(@"tmp  is %@",[formatter stringFromDate:tmp]);

to check, if it is correct, what I said, change the format to contain the time components.

formatter.format = [@"yyyy-MM-dd HH:mm"];
NSLog(@"tmp  is %@",[formatter stringFromDate:tmp]);

The formatter will also take "oddities" like Leap Day, Leap Month (yes — those exits), Daylight Saving Times, Leap Seconds … in account — accordantly to the current calendar.


A great WWDC 2011 Video: Performing Calendar Calculations — a must-see for every cocoa developer.


BTW: to print a object with NSLog you dont need to call -description on it to pass in a string. NSLog will do this internally.

NSLog(@"tmp  is %@", tmp);

is just fine.

Upvotes: 2

Sulthan
Sulthan

Reputation: 130200

The answer is simple, NSLog just converts the NSDate to a NSString, using its formatter with GMT (zero) timezone.

Your formatter is by default set to your default time zone, which is probably -4:00. When you print it out, NSLog converts it to 0:00, adding 4 hours.

In general, it's unsafe to parse dates without specifying their timezone.

Upvotes: 1

Related Questions