Siddharth Bhatt
Siddharth Bhatt

Reputation: 613

NSDateFormatter dateFromString returns wrong date even when TimeZone details supplied with string

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

[dateFormat setDateFormat:@"EEEE','dd MMM YYYY z"];

NSString *string = @"Thursday,11 Jun 2015 +0530";

NSDate *tempDate = [dateFormat dateFromString:string];

Now when I NSLog..

NSLog(@"%@",[tempDate description]);

2014-12-24 18:30:00 +0000

NSLog(@"%@",[dateFormat stringFromDate:tempDate]);

Thursday,25 Dec 2014 IST

Why is it not showing 'Thursday,11 Jun 2015 IST' instead 'Thursday,25 Dec 2014 IST' ?

Upvotes: 0

Views: 262

Answers (3)

Shridhar Mali
Shridhar Mali

Reputation: 189

if you change to 'yyyy' will show you result like.

Thursday,11 Jun 2015 +0530

NSDateFormatter *dateFormattor = [[NSDateFormatter alloc] init];
[dateFormattor setDateFormat:@"EEEE','dd MMM yyyy zzzz"];
 NSTimeZone *_timezone = [NSTimeZone timeZoneWithName:@"IST"];
[dateFormattor setTimeZone:_timezone];
NSString *string = @"Thursday,11 Jun 2015 +0530";
NSDate *tempDate = [dateFormattor dateFromString:string];
NSLog(@"tempDate is :%@",tempDate);
NSLog(@"%@",[dateFormattor stringFromDate:tempDate]);

Thursday,11 Jun 2015 India Standard Time

change in line at 'z' char you get different results.

[dateFormattor setDateFormat:@"EEEE','dd MMM yyyy zzzz"];
  1. z = GMT+0530 IST
  2. zz = GMT+0530 IST
  3. zzz = GMT+0530 IST
  4. zzzz = India Standard Time IST
  5. zzzzz = India Standard Time IST

Hope this will help.

Upvotes: 2

Chetan Prajapati
Chetan Prajapati

Reputation: 2307

NSDateFormatter *outDateFormatter = [[NSDateFormatter alloc] init];
outDateFormatter.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"IST"];
outDateFormatter.dateFormat = (your date formate)

Try using this

Upvotes: 0

Siddharth Bhatt
Siddharth Bhatt

Reputation: 613

I changed 'YYYY' to 'yyyy' and it worked. Thanks for reading this.

Upvotes: 1

Related Questions