-2

Following is the code I am writing to convert UTC time to local time :

NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc] init];
    [dateFormatter1 setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"];
    NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
    [dateFormatter1 setLocale:locale];
    NSDate *date = [dateFormatter1 dateFromString:dateString];

    dateString = [date descriptionWithLocale:[NSLocale systemLocale]];

    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];

    NSDateFormatter *dateFormatters = [[NSDateFormatter alloc] init];
    [dateFormatters setDateFormat:@"HH:mm"];
    [dateFormatters setTimeZone:[NSTimeZone systemTimeZone]];
    dateString = [dateFormatters stringFromDate: destinationDate];  

But this way I am getting a difference of 1 hour. i.e. if date displayed on web app is 12:30, on the app it is displayed as 13:30. Why is that so ?

Nitish
  • 13,845
  • 28
  • 135
  • 263

2 Answers2

0

Try with this code:

- (NSDate *) UTCTimeToLocalTime
{
    NSTimeZone *tz = [NSTimeZone defaultTimeZone];
    NSInteger seconds = [tz secondsFromGMTForDate: yourDate];
    return [NSDate dateWithTimeInterval: seconds sinceDate: yourDate];
}

- (NSDate *) LocalTimeToUTCTime
{
    NSTimeZone *tz = [NSTimeZone defaultTimeZone];
    NSInteger seconds = -[tz secondsFromGMTForDate: yourDate];
    return [NSDate dateWithTimeInterval: seconds sinceDate: yourDate];
}
BADRI
  • 643
  • 8
  • 26
-1

You need to learn and accept the principles of handling times and dates.

NSDate represents points in time, independent of any time zone. If we are talking on the phone, and our computers calculate [NSDate date], they get the exact same date, even if our watches display totally different times.

Calendars with time zone information transform between NSDate and something that a user in one particular part of the world expects. So the same NSDate is converted to a string to match what your watch displays, or what my watch displays, which would be different. There should be no need to modify an NSDate in any of this, as you did.

gnasher729
  • 51,477
  • 5
  • 75
  • 98