-1

My server returns date data as local timezone timestamps.

On the client-side, I want to display those dates as local date strings. If I do the following, I got the wrong date ("6/30/2014" instead of "7/01/2014")

var ts = 1404172800;
new Date(1404172800*1000).toLocaleDateString()
>>>"6/30/2014" 

To prevent this problem, I suppose I have to convert the local timezone timestramp I receive from the server to UTC timestamp before creating the new Date() object.

Am I right? What is the best way to achieve that that will work in most browsers?

Edit:

I confirm that the real date in local time zone should be 7/01/2014. That's local Eastern time UTC -5(-4). but the new Date() object thinks this is UTC but it's not. I suppose it's because the date is returned as a timestamp without having been converted to UTC.

Below the Radar
  • 7,321
  • 11
  • 63
  • 142
  • 1
    Possible duplicate of [How do you convert a Javascript timestamp into UTC format?](https://stackoverflow.com/questions/4380469/how-do-you-convert-a-javascript-timestamp-into-utc-format) – DSCH Oct 04 '18 at 13:26
  • `6/30/2014` *could* be correct. – Salman A Oct 04 '18 at 14:04
  • I confirm that the real date in local time zone should be 7/01/2014. That's local Eastern time UTC -5(-4). but the new Date() object thinks this is UTC but it's not. I suppose the problem is that the date is returned as a timestamp without having been converted to UTC. – Below the Radar Oct 04 '18 at 16:56

1 Answers1

2

Isn't that right already? Timestamps are always in UTC.

You're seeing 30th June and not 1st of July because when that event happened, in the local time zone, it was still 30th of June. For example, for me it is showing as 1st of July in IST.

enter image description here

Also, this timestamp represents an event which occurred at 1st July 2014 at 00:00:00 GMT exactly. India is GMT+05:30, as you can see in the screenshot - so if the local timezone, even if it is GMT minus one minute, it would still be 30th of June there.

rmn
  • 1,119
  • 7
  • 18
  • I confirm that the real date in local time zone should be 7/01/2014. That's local. but the new Date() object thinks this is UTC but it's not. – Below the Radar Oct 04 '18 at 15:17
  • @BelowtheRadar What's the local time zone? – rmn Oct 04 '18 at 15:20
  • Eastern time UTC -5(-4). The problem, I suppose is that the date is returned as a timestamp without having been converted to UTC – Below the Radar Oct 04 '18 at 16:39
  • Date takes in a timestamp, timestamps are always UTC, your timestamp 1404172800000 translates to 1st July 2014 00:00:00, your timezone is UTC -5, which translates this to 30th June 2014 19:00:00, so your code works fine. If you're still positive this is producing the wrong result, you need to check your server side code. – rmn Oct 04 '18 at 17:10
  • Ok you are right! Timestamp should always be in UTC so I should work on server side – Below the Radar Oct 04 '18 at 17:13