1

I'm having this issue where the correct time is passed but once it hits the [formatter setDateFormat:date] it comes out in a different time zone. Here is a snippet

NSDate* date = user.startDate;
NSDateFormatter *format = [[NSDateFormatter alloc] init];
NSLog(@"-------> (1) time is %@", date);
NSLog(@"-------> (2) time is %@", date);
[format setDateFormat:@"h:mm a"];
NSLog(@"-------> (3) time is %@", date);
NSLog(@"-------> (4) time is %@", [format stringFromDate:date]);

Here is the debugger output for the log messages

-------> (1) time is 2016-06-30 09:25:17 +0000
-------> (2) time is 2016-06-30 09:25:17 +0000
-------> (3) time is 2016-06-30 09:25:17 +0000
-------> (4) time is 2:25 AM

I'm expecting the output for (4) to be time is 9:25 AM

Eiko
  • 25,601
  • 15
  • 56
  • 71
ioskaveen
  • 196
  • 1
  • 4
  • 14
  • I removed code that's irrelevant to your question (but kept the duplicate lines in so that the references in the answers remain valid). – Eiko Jun 30 '16 at 17:43
  • Note that (1), (2), (3) are just doing the exact samt thing. The date is immutable and the same instance, and you're not using a formatter. – Eiko Jun 30 '16 at 17:45

2 Answers2

1

Here's what is going on: the log of a date will always be GMT. (I don't think it makes sense for me to get into details as there is a great explanation here.) That means that log 1, 2 and 3 will be “wrong” (not in your timezone) and that should be expected.

If, for instance, you want to log the string as GMT, you can change the property timeZone of your date formatter.

Dealing with dates can be extremely hard. Please take the time to read if not all, some important parts of this document (fundamentals/basics).

Community
  • 1
  • 1
Alberto S.
  • 81
  • 6
1

Your time zone is apparently UTC-7000.

NSLog prints NSDate objects always in UTC, NSDateFormatter considers the current time zone. The printed dates are actually the same.

If you really need all dates in UTC, set the time zone of the formatter.

format.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];

By the way: There are built-in methods to check if a date is in today or yesterday.

vadian
  • 274,689
  • 30
  • 353
  • 361