Jan
Jan

Reputation: 11

NSDateFormatter behavior problem

I have a problem using NSDateFormatter in iPhone programming. Below is my code snippet.

NSString *inputDate = @"2011-03-14";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd"];
NSDate *entryDate = [formatter dateFromString:inputDate];
[formatter release]

The result I am getting is

2011-03-13 16:00:00 +0000

which is the GMT equivalent of 2011-03-14 00:00:00. (My time zone is GMT +08:00)

Why I am getting this? How to get 2011-03-14 00:00:00 as the result?

Thanks.

~Jan

Upvotes: 1

Views: 571

Answers (3)

HyLian
HyLian

Reputation: 5093

You can try to add the timezone to your original string

NSString *inputDate = @"2011-03-14+0800";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-ddZZZ"];
NSDate *entryDate = [formatter dateFromString:inputDate];
[formatter release]

Upvotes: 0

hennes
hennes

Reputation: 9342

You can set the timezone using

[formatter setTimeZone:...]

. Alternatively I would try to just set the formatter's locale by

NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"..."];
[formatter setLocale:locale];

Upvotes: 2

visakh7
visakh7

Reputation: 26390

Pls take a look at this

NSDateFormatter returns unexpected results

This is what Apple recommends

Upvotes: 0

Related Questions