-3
- (void) dateConverter{
    NSString *string = [NSString stringWithFormat:@"%@ %@", [[self dates]objectAtIndex:0], [times objectAtIndex:0]]; // string = 01-10-2014 11:36 AM;
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

    [dateFormatter setDateFormat:@"dd-MM-yyyy hh:mm a"];
    [dateFormatter setLocale:[NSLocale currentLocale]];
    NSDate *date = [[NSDate alloc] init];

    date = [dateFormatter dateFromString:string];
    NSLog(@"dateFromString = %@", date); // 2014-10-01 18:36:00 +0000

    NSTimeInterval timeInterval = [date timeIntervalSince1970];
    NSLog(@"dateFromString = %f", timeInterval); // 1412188560.000000
}

I am converting the string to actual date object, but I am getting different behavior

string = 01-10-2014 11:36 AM

is actual value I am trying to convert but getting this

2014-10-01 18:36:00 +0000

what is wrong with it?

S.J
  • 3,063
  • 3
  • 33
  • 66

1 Answers1

2

The problem is a display issue.

You are using the default date formatter to print the date (NSLog used the description method).

The time is displayed in UTC (GMT) and it looks like you are in timezone -0700. The time is being displayed in timezone offset 0000.

The date/time in the system is based on the GMT time, that way times can be compared across timezones and everywhere on Earth the time is the same in the system at the same time.

Use a date formatter to get the date/time in the format you want.

Example code:

NSString *dateString = @"01-10-2014 11:36 AM";
NSLog(@"dateString = %@", dateString);
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

[dateFormatter setDateFormat:@"dd-MM-yyyy hh:mm a"];
[dateFormatter setLocale:[NSLocale currentLocale]];
NSDate *date = [[NSDate alloc] init];

date = [dateFormatter dateFromString:dateString];
NSLog(@"dateFromString = %@", date);

NSString *displayDate = [dateFormatter stringFromDate:date];
NSLog(@"displayDate = %@", displayDate);

Output:

dateString = 01-10-2014 11:36 AM
dateFromString = 2014-10-01 15:36:00 +0000
displayDate = 01-10-2014 11:36 AM

Note: You can supply your own date format to get exactly the format what you want.

zaph
  • 111,848
  • 21
  • 189
  • 228
  • I did this NSLog(@"date: %@", [date description]); but result is same :(. Ans I also "po date" in console but result is same. – S.J Oct 30 '14 at 16:03
  • Yes, because `NSLog` uses the `description` method. Apple displays the date the way they want to, in GMT (UTC). You are not in the GMT timezone. Use your own date formatter, see the addition to the answer. – zaph Oct 30 '14 at 16:04
  • Sir you are marvelous. Thanks a lot. – S.J Oct 30 '14 at 16:09
  • @S.J seems you got it from second time, http://stackoverflow.com/questions/26646455/need-assistance-regarding-nsdateformatter/26646882#26646882 – l0gg3r Oct 30 '14 at 16:17
  • @zaph Sir if I am trying to convert "date" in time interval I am getting same issue of time zone, how can I fix that? – S.J Oct 31 '14 at 16:41