35

In my iPhone application i am very struggling to convert the webservice response time to current device time. The webservice time in UTC-5 timezone. The app is worldwide use app. So i have to convert the response time to current device timezone. This is simple messaging app.

When i have sent a message the time is "5:05 PM" (India Chennai timezone) but when am retrieve time from webservice is "2012-07-16 07:33:01". When i show the time in the app i should convert the time to device's local time. I have tried in some way but i can't solve yet. Code is:

NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc] init]; 
[dateFormatter1 setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; 
[dateFormatter1 setLocale:[NSLocale currentLocale]];
//[dateFormatter1 setTimeZone:[NSTimeZone timeZoneWithName:@"IST"]];
[dateFormatters setTimeZone:[NSTimeZone systemTimeZone]];
NSDate *date = [dateFormatter1 dateFromString:dateStr];
NSLog(@"date : %@",date);

But the output date and time is 2012-07-16 02:03:01 +0000 I have stored this date/time in Coredata and when I have retrieve from CoreData and covert to NSString using the below code,

NSDateFormatter *dateFormatters = [[NSDateFormatter alloc] init];
[dateFormatters setDateFormat:@"dd-MMM-yyyy hh:mm"];
[dateFormatters setDateStyle:NSDateFormatterShortStyle];
[dateFormatters setTimeStyle:NSDateFormatterShortStyle];
[dateFormatters setDoesRelativeDateFormatting:YES];
[dateFormatters setTimeZone:[NSTimeZone systemTimeZone]];  
dateStr = [dateFormatters stringFromDate:dateString];
NSLog(@"DateString : %@", dateStr);

The output date and time is "Today 7:33 AM". It should be show "Today 5:05 PM". Can anyone please save my day? Please help to solve this issue. Thanks in advance.

Krunal
  • 77,632
  • 48
  • 245
  • 261
Gopinath
  • 5,392
  • 21
  • 64
  • 97
  • 2
    I see a couple typos that worry me, the MMM for month in your second block and case inconsistency for hour between the two blocks – Eric Jul 16 '12 at 13:03
  • @Eric Thanks. But, i can't understand what you are saying? Could you please explain? Thanks. – Gopinath Jul 16 '12 at 13:06
  • Post the exact sample of the time format received from webcervice, you'll need to add the timezone literal to the format string. – A-Live Jul 16 '12 at 13:06
  • @A-Live I have made bold the webservice date and time format. I have spent 2 fulldays to solve this issue. Still i'm looking for the solution. Can you pleas help me to solve this? Thanks. – Gopinath Jul 16 '12 at 13:11
  • 2
    Then use the following format: @"yyyy-MM-dd HH:mm:ss Z" where Z is responsible for the timezone, add @" -0500" to every time string you need to parse and that will do it. What `Gopinath` is mentioned is that your input and output formats are not the same, keep that in mind and don't try to parse the formatted string back to date. – A-Live Jul 16 '12 at 13:18
  • @A-Live Thanks for your helping hand. If you don't mind can you please explain your answer? Where i need to add @"-0500" in my code. Thanks. – Gopinath Jul 16 '12 at 13:25
  • @A-Live When i have changed the format: @"yyyy-MM-dd HH:mm:ss Z". The output showing Null; Could you please help me? Thanks. – Gopinath Jul 16 '12 at 13:27
  • Did you add the timezone part to the string ? That is @" -0500", i've lost the space after the first quote for some reason. – A-Live Jul 16 '12 at 13:28
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/13939/discussion-between-gopinath-and-a-live) – Gopinath Jul 16 '12 at 13:36

3 Answers3

78

I have tested your scenario and added some code for your reference. Please test the below and please let me know it is useful for you.

NSString *dateStr = @"2012-07-16 07:33:01";
NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc] init]; 
[dateFormatter1 setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; 
NSDate *date = [dateFormatter1 dateFromString:dateStr];
NSLog(@"date : %@",date);

NSTimeZone *currentTimeZone = [NSTimeZone localTimeZone];
NSTimeZone *utcTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];

NSInteger currentGMTOffset = [currentTimeZone secondsFromGMTForDate:date];
NSInteger gmtOffset = [utcTimeZone secondsFromGMTForDate:date];
NSTimeInterval gmtInterval = currentGMTOffset - gmtOffset;

NSDate *destinationDate = [[[NSDate alloc] initWithTimeInterval:gmtInterval sinceDate:date] autorelease];

NSDateFormatter *dateFormatters = [[NSDateFormatter alloc] init];
[dateFormatters setDateFormat:@"dd-MMM-yyyy hh:mm"];
[dateFormatters setDateStyle:NSDateFormatterShortStyle];
[dateFormatters setTimeStyle:NSDateFormatterShortStyle];
[dateFormatters setDoesRelativeDateFormatting:YES];
[dateFormatters setTimeZone:[NSTimeZone systemTimeZone]];  
dateStr = [dateFormatters stringFromDate: destinationDate];
NSLog(@"DateString : %@", dateStr);

Thanks.

rjv
  • 6,058
  • 5
  • 27
  • 49
Yuvaraj.M
  • 9,741
  • 16
  • 71
  • 100
  • 1
    @Yuvaraj.M would you be willing to add some comments to the three lines of offset and interval calculations? I'm not quite following. – Murray Sagal Mar 13 '13 at 20:46
  • Are these calculation take care of DST As well ? If not then plz tell me how i can take care of DST in time . – Prashant Vashisht Apr 14 '15 at 06:09
  • @Yuvaraj.M Thanks, your code is works but it give time is 1 hour ago compare from my local device time e.g : my device time is 8:00 AM And this code give time 9:00 AM. can you help me out. – Nilesh Feb 17 '16 at 14:31
  • I just love how this starts with **Mr** Lol ! – GoodSp33d Aug 10 '16 at 04:21
11
NSDate* currentDate = [NSDate date];

NSTimeZone* CurrentTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
NSTimeZone* SystemTimeZone = [NSTimeZone systemTimeZone];

NSInteger currentGMTOffset = [CurrentTimeZone secondsFromGMTForDate:currentDate];
NSInteger SystemGMTOffset = [SystemTimeZone secondsFromGMTForDate:currentDate];
NSTimeInterval interval = SystemGMTOffset - currentGMTOffset;

NSDate* TodayDate = [[NSDate alloc] initWithTimeInterval:interval sinceDate:currentDate];
NSLog(@"Current time zone Today Date : %@", TodayDate);

Swift 4

var currentDate = Date()
var CurrentTimeZone = NSTimeZone(abbreviation: "GMT")
var SystemTimeZone = NSTimeZone.system as NSTimeZone
var currentGMTOffset: Int? = CurrentTimeZone?.secondsFromGMT(for: currentDate)
var SystemGMTOffset: Int = SystemTimeZone.secondsFromGMT(for: currentDate)
var interval = TimeInterval((SystemGMTOffset - currentGMTOffset!))
var TodayDate = Date(timeInterval: interval, since: currentDate)
print("Current time zone Today Date : \(TodayDate)")

Hope it helps to another developers ! Happy Coding !

Mahesh Cheliya
  • 1,334
  • 1
  • 16
  • 21
  • Can u pls post it in swift? – Chandni Feb 15 '18 at 17:04
  • @Chandni - May this help you - [UTC/GMT ⟺ Local](https://stackoverflow.com/questions/11504843/get-current-iphone-device-timezone-date-and-time-from-utc-5-timezone-date-and-ti/48867259#48867259) – Krunal Feb 19 '18 at 13:27
5

May this extension would be easier.

Swift 4: UTC/GMT ⟺ Local (Current/System)

extension Date {

    // Convert local time to UTC (or GMT)
    func toGlobalTime() -> Date {
        let timezone = TimeZone.current
        let seconds = -TimeInterval(timezone.secondsFromGMT(for: self))
        return Date(timeInterval: seconds, since: self)
    }

    // Convert UTC (or GMT) to local time
    func toLocalTime() -> Date {
        let timezone = TimeZone.current
        let seconds = TimeInterval(timezone.secondsFromGMT(for: self))
        return Date(timeInterval: seconds, since: self)
    }

}


// Try it
let utcDate = Date().toGlobalTime()
let localDate = utcDate.toLocalTime()

print("utcDate - (utcDate)")
print("localDate - (localDate)")
Krunal
  • 77,632
  • 48
  • 245
  • 261