0

I am trying to convert my date string to NSDate but its return correct date and wrong time.

This is my code :

    NSString *dateStr = @"2013-12-20 12:10:40";

    // Convert string to date object
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat: @"yyyy-MM-dd HH:mm:ss"];
    NSDate *lastUpdatedate = [dateFormatter dateFromString:dateStr];

    NSLog(@"lastUpdatedate : %@",lastUpdatedate);

It returns this :

lastUpdatedate : 2013-12-20 06:40:40 +0000
Shaik Riyaz
  • 11,204
  • 7
  • 53
  • 70

4 Answers4

2

- [NSDate description] (which is called when passing it to NSLog) always prints the date object in GMT timezone, not your local timezone. If you want an accurate string representation of the date, use a date formatter to create a correct string according to your timezone.

Léo Natan
  • 56,823
  • 9
  • 150
  • 195
2

As @Leo Natan said, - [NSDate description] always gives date in GMT timezone. If you want to convert into local timezone then use following code.

NSString *dateStr = @"2013-12-20 12:10:40";

// Convert string to date object
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter setDateFormat: @"yyyy-MM-dd HH:mm:ss"];
NSDate *lastUpdatedate = [dateFormatter dateFromString:dateStr];

NSLog(@"lastUpdatedate : %@",[self getLocalTime:lastUpdatedate]);



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

OUTPUT:

lastUpdatedate : 2013-12-20 12:10:40 +0000

Dilip Manek
  • 9,095
  • 5
  • 44
  • 56
MilanPanchal
  • 2,943
  • 1
  • 19
  • 37
1
NSString *dateStr = @"2013-12-20 12:10:40";
NSDateFormatter *dateFormatterTest = [[NSDateFormatter alloc] init];
[dateFormatterTest setDateFormat: @"yyyy-MM-dd HH:mm:ss"];
[dateFormatterTest setLocale:[NSLocale currentLocale]];
NSDate *d = [dateFormatterTest dateFromString:dateStr];

Set NSLocale in your code, and you get perfect result.

Nirmalsinh Rathod
  • 5,079
  • 4
  • 26
  • 56
0

You can try this:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat: @"yyyy-MM-dd HH:mm:ss"];
[dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];

NSDate *lastUpdatedate = [dateFormatter dateFromString:dateStr];

NSTimeInterval sourceGMTOffset = [[NSTimeZone systemTimeZone] secondsFromGMTForDate:lastUpdatedate];

lastUpdatedate = [lastUpdatedate dateByAddingTimeInterval:sourceGMTOffset];

NSLog(@"lastUpdatedate : %@",lastUpdatedate);
Bhumeshwer katre
  • 4,671
  • 2
  • 19
  • 29