returns a date an hour in the future

I'm getting the current date/time using [NSDate date]. The value returned is an hour in the future. I've check my phones location & time settings and they are correct.

I can display the correct date and time as a string using the code below.

[NSDateFormatter localizedStringFromDate:[NSDate date] dateStyle:NSDateFormatterShortStyle 
                                                       timeStyle:NSDateFormatterShortStyle]

But I need it to return the correct date/time as a date object as I use it to calculate the estimated time of arrival using -

[date dateByAddingTimeInterval:interval]

I realise my question is similar to this one already asked but none of the answers suit my needs. Thanks in advance!

init] returning date an hour in the past?


Solution 1:

Maybe you are confusing the point in time (ie the NSDate object) and the point in time at your location (ie your local time).

If you print a NSDate (like NSLog(@"%@", [NSDate date]); which invokes [date description]) the date representation that is printed is in UTC timezone (+0000) (at least it is on my computer).
So as long as you don't live in an area that uses UTC the date printed by [date description]; is always "wrong". But wrong only means that its representation is not the same representation as the clock in your office. The date (as in point in time) is still correct.

When you use localizedStringFromDate:dateStyle:timeStyle: you are printing the date in your local timezone.

NSDate *date = [NSDate date];
NSLog(@"%@", date);
NSLog(@"%@", [NSDateFormatter localizedStringFromDate:date dateStyle:NSDateFormatterShortStyle timeStyle:NSDateFormatterShortStyle]);

at my computer this results in:

2011-02-12 08:32:10.658 x[75647:207] Date: 2011-02-12 07:32:10 +0000
2011-02-12 08:32:10.661 x[75647:207] Date: Saturday, February 12, 2011 8:32:10 AM Central European Time

the printed strings are different, but the NSDate object is still the same. That's why you have to use NSDateFormatters when you show a date to the user. Because the same point in time looks different on different places of the world.


But there are only three places where an UTC formatted date would be one hour in the future, so if you don't live in greenland, cape verde or on the azores I might be totally wrong and there is something wrong with your NSDate objects.


Edit: Out of curiosity I read the documentation about [date description] again. And it says

A string representation of the receiver in the international format YYYY-MM-DD HH:MM:SS ±HHMM, where ±HHMM represents the time zone offset in hours and minutes from GMT (for example, “2001-03-24 10:45:32 +0600”).

So I don't know why the date at my computer is printed in GMT timezone. It might be in another timezone at your computer.
But still, it's only the representation, the date is still the same.