Vijay
Vijay

Reputation: 1016

Convert date and time to local date and time format

I am facing issue while converting date and time in device's current (Local) date and time. Am getting date in format 2013-04-03 01:07:56 +0000 from API and I want to convert this date in local date and time format and display. Can anyone please suggest me how can I achieve this?

Upvotes: 0

Views: 1455

Answers (1)

Kirtikumar A.
Kirtikumar A.

Reputation: 4204

Just set the timeZone in the dateFormatter, This code is enough

NSString *dateString = @"24 08 2011 09:45PM";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd MM yyyy hh:mma"];
NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"BST"];
[dateFormatter setTimeZone:sourceTimeZone];
NSDate *dateFromString = [dateFormatter dateFromString:dateString];

The dateFromString will now have the date 24 08 2011 08:45PM(GMT).. Then to convert this to string with local time just code the following,

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[formatter setTimeZone:[NSTimeZone localTimeZone]];
[formatter setLocale:[NSLocale systemLocale]];

[dateFormatter setDateFormat:@"dd MM yyyy hh:mma"];
NSString *stringFromDAte = [dateFormatter stringFromDate:dateString];

Upvotes: 2

Related Questions