0

I am using following code to get current date:

-(NSDate*) timeStampDate {
    NSDate* currentDate = [NSDate date];

    return [NSDate dateWithTimeInterval:
            [[NSTimeZone defaultTimeZone] secondsFromGMTForDate: currentDate]
                              sinceDate: currentDate];
}

When I display this date immediately upon saving, using a category that puts it into plain english, it gives me "5 hours ago". As I am in New York, this suggests to me the date is really the Greenwich date. Can anyone please explain to me what the above code is really doing.

luk2302
  • 55,258
  • 23
  • 97
  • 137
user1904273
  • 4,562
  • 11
  • 45
  • 96

2 Answers2

2

You're getting the current date: [NSDate date]

Then you're getting the number of seconds between the default timezone and GMT at that date: [[NSTimeZone defaultTimeZone] secondsFromGMTForDate: currentDate]

Then you're calculating a new date that is the current date + those seconds. The interval is negative, so you're calculating a date in the past: [NSDate dateWithTimerInterval:-seconds sinceDate:currentDate

Since your interval is -5 hours, subtracted from now, then you have calculated a new date that was indeed "5 hours ago."

If your goal is to get the time in GMT, I suggest using a date formatter as shown in the highest-voted answer here: NSDate - Convert Date to GMT

Community
  • 1
  • 1
Thunk
  • 4,099
  • 7
  • 28
  • 47
  • So in order to get a date that will format correctly to the actual current time where user is, I should remove the time interval part? Formatting is done in the category that converts into plain English. – user1904273 Jan 09 '16 at 18:31
  • 1
    `[NSDate date]` will give you the current time for whatever timezone is set on the device. Based on what you've said, that sounds like all you need. – Thunk Jan 10 '16 at 07:09
0

I don't understand why that result does not seem logical - you are asking for seconds from GMT right now for the timezone you are in, which is about five hours as you say. If the date were any "older", the seconds would be greater.

All NSDates are created and live independent of any particular timezone, but that does not matter.

Kendall Helmstetter Gelner
  • 74,769
  • 26
  • 128
  • 150