Create date from Unix Timestamp ignoring timezone

For the oData Rest service, I use Moment.js to create a date from a Unix timestamp, and I would like to ignore the time zone. My date is "2013-12-24", which is 1387839600 in Unix seconds.

Using

moment("2013-12-24", "YYYY-MM-DD").toISOString() 

leads to "2013-12-23T23: 00: 00.000Z" since I live in GMT + 1. Using

 moment.utc("2013-12-24", "YYYY-MM-DD").toISOString() 

I get "2013-12-24T00: 00: 00.000Z", which is what I want. I can simply remove the Zulu time ā€œZā€ at the end.

But my real representation of the date is the Unix timestamp. So if i do

 moment.utc(1387839600, "X").toISOString() 

I always get "2013-12-23T23: 00: 00.000Z", but I want him to return "2013-12-24T00: 00: 00.000Z".

Where is my fault Thank you for your help!

+7
javascript date datetime momentjs
source share
4 answers

Unix timestamps, whether in seconds or milliseconds, are always in UTC. The value 1387839600 is really 2013-12-23 at 11:00 UTC. You use sites like this to check.

If you want it to be at 2013-12-24 at midnight UTC, the timestamp would be 1387843200 .

So, the moment behaves correctly. Instead, you should focus on your leisure API and make sure it emits UTC correctly, not the local time value.

Also, if you only need a portion of the date, do not use .toISOString . Use .format , for example:

 moment.utc(1387843200, 'X').format('YYYY-MM-DD') 
+16
source share

You can make your own format. Any lines that need to be copied somehow (not interpolated) must be contained in brackets.

So, in your situation, this should work:

 moment(1387839600, 'X').format('YYYY-MM-DD[T00:00:00.000]') 
+5
source share

After setting up the onChange function, for example

<DateTimeField mode="date" inputFormat='MM-DD-YYYY' onChange= {this.onChange} />

The onChange function might look like this:

onChange: function(value) { console.log({myDate: moment.utc(value, 'x').format('YYYY-MM-DDTHH:mm:ss.SSSZ')}); },

The onChange value appears to appear as a Unix ms (x) timestamp, not a Unix (X) timestamp in case it is ever confusing.

This should print a line like 2015-07-15T15:02:00.000+00:00

+2
source share

Do not use toISOString() . Instead, use something like this:

 moment.utc(1387839600, "X").utcOffset(1).format('YYYY-MM-DD') + "[T" + moment.utc(1387839600, "X").utcOffset(1).format('HH:mm:ss.000]') 
+1
source share

All Articles