iOS: Date not converting correctly

314 views Asked by At

Say for instance, I have a date: 2014-11-24 12:24:25 stored in an NSString variable.

I'm trying to convert that to an NSDate object so that I can calculate a future date:

NSDate *futureTimeStamp;

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd hh:mm:ss"];

NSDate *oldDate = [dateFormatter dateFromString:timestamp];

It keeps telling me that the old date time is: 2014-11-24 06:46:06 +0000 which isn't correct.

Any ideas why it's not converting it correctly?

Update #1:

timestamp is a string. Stored in that variable is: 2014-11-24 12:58:40

When I print out oldDate, it shows this in the 2014-11-24 06:58:40 +0000

2

There are 2 answers

10
mikemike396 On BEST ANSWER

Try converting to the local date from UTC

  NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  [dateFormatter setDateFormat:@"yyyy-MM-dd hh:mm:ss"];
  NSDate *date = [dateFormatter dateFromString:timestamp];
  NSTimeZone *currentTimeZone = [NSTimeZone localTimeZone];
  NSTimeZone *previousTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];
  NSInteger currentGMTOffset = [currentTimeZone secondsFromGMTForDate:date];
  NSInteger currentOffset = [previousTimeZone secondsFromGMTForDate:date];
  NSTimeInterval gmtInterval = currentGMTOffset - currentOffset;
  NSDate *localDate = [[NSDate alloc] initWithTimeInterval:gmtInterval sinceDate:date];
4
ios On

You can make time shifting like:

NSDate *date = [oldDate dateWithTimeIntervalSinceReferenceDate:milliseconds];