mrugen munshi
mrugen munshi

Reputation: 3607

Issues with dateformatter in iphone

I am getting a NSDate *newDate value as 2011-08-12 13:00:00 +0000. Now when I try to convert it to a string by dateformatter as follows:

NSDateFormatter *dateFormatter= [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd h:mm:ss Z"];

NSString *datestr = [[dateFormatter stringFromDate:newDate] lowercaseString]; 

But the value which I get for datestr is 5:30 hours more than the newDate value. I don't know where I am wrong. I get value for datestr as 2011-08-12 18:30:00 + 5:30 (which is incorrect).

Upvotes: 0

Views: 1276

Answers (2)

Delete
Delete

Reputation: 922

Looks like it must be a timezone / UTC thing. The date is probably being returned in global / universal time and what you want is the local time.

According to the IOS documentation: https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSDateFormatter_Class/Reference/Reference.html - seems you could try including a locale in order to specify which time zone you want.

NSDate *date = [NSDate dateWithTimeIntervalSinceReferenceDate:118800];

NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
[dateFormatter setLocale:usLocale];

NSLog(@"Date for locale %@: %@",
  [[dateFormatter locale] localeIdentifier], [dateFormatter stringFromDate:date]);

Upvotes: 0

Bushra Shahid
Bushra Shahid

Reputation: 3579

It is basically converting the time to your local time zone. if you dont want that just set the time aone for date formatter:

[dateFormatter setTimeZone:[NSTimeZone <use any of the functions below to get your desired one>]];

Documentation link: http://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSTimeZone_Class/

Creating and Initializing Time Zone Objects
+ timeZoneWithAbbreviation:
+ timeZoneWithName:
+ timeZoneWithName:data:
+ timeZoneForSecondsFromGMT:
– initWithName:
– initWithName:data:
+ timeZoneDataVersion
Working with System Time Zones
+ localTimeZone
+ defaultTimeZone
+ setDefaultTimeZone:
+ resetSystemTimeZone
+ systemTimeZone

Upvotes: 2

Related Questions