3

I am fetching data from the server and part of that data is time. Time is stored in UTC in my DB so what I'm returning is also in UTC. For example: 2014-05-22 05:12:40

Further, I am using the DateTools to show the time difference on the device like X hours ago or X minutes ago etc....

The problem is that when the UTC time coming from the server is compared to the local time there is a huge difference. Something that should say X seconds ago says X hours ago because of the time difference.

Question

How can I convert the date coming from the server to the local time zone set on the device?

This is what I'm doing right now:

@date_formatter = NSDateFormatter.alloc.init
@date_formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
@date_from_server = "2014-05-22 05:12:40"
@date = @date_formatter.dateFromString(@date_from_server)
@time.text = @date.shortTimeAgoSinceNow
birdy
  • 9,286
  • 24
  • 107
  • 171

3 Answers3

2

I don't know how it is done in ruby motion but in Objective-C, it is done as follows :

1.) Create an instance of NSDateFormatter class

2.) Set a specific date format string of it, and also you set the specific time zone of it

3.) Get a date from the incoming string via the dateformatter instance

4.) Change the time zoneof the date formatter instance to the local time zone

5.) Convert the date obtained previously to the new time zone .

In Objective-C

NSDateFormatter* df = [[NSDateFormatter alloc] init];
[df setDateFormat:incomingDateFormat];
[df setTimeZone:incomingTimeZone]; // Can be set to @"UTC"

NSDate *date = [df dateFromString:incomingDateString];

[df setDateFormat:newDateFormat];
[df setTimeZone:newTimeZone]; //// Can be set to [NSTimeZone localTimeZone]

NSString *newDateStr = [df stringFromDate:date];

I believe the same can be done in Rubymotion too.

Zen
  • 3,047
  • 1
  • 20
  • 18
1
NSDateFormatter *formater = [[NSDateFormatter alloc] init];
formater.dateFormat = @"yyyy-MM-dd HH:mm:ss";
NSString *datestr = @"2014-05-22 05:12:40";
formater.timeZone = [NSTimeZone localTimeZone];
NSDate *date = [[formater dateFromString:datestr] dateByAddingTimeInterval:formater.timeZone.secondsFromGMT];
Siverchen
  • 379
  • 2
  • 16
0
NSDateFormatter *df=[[[NSDateFormatter alloc] init] autorelease];
    // Set the date format according to your needs
    [df setTimeZone:[NSTimeZone timeZoneWithName:@"America/Toronto"]];
    //[df setDateFormat:@"MM/dd/YYYY HH:mm "]  // for 24 hour format
    [df setDateFormat:@"YYYY-MM-dd HH:mm:ss"];// for 12 hour format

Try this

madhu
  • 961
  • 9
  • 21