简体   繁体   中英

Create date from Unix Timestamp ignoring timezone

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

Using

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

results in "2013-12-23T23:00:00.000Z", since I live in GMT+1. By the use of

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

I get "2013-12-24T00:00:00.000Z" which is exactly what I want. I can simply remove Zulu time's "Z" at the end.

But my date's real representation is a Unix timestamp. So if I do

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

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

Where's my fault? Thanks for your help!

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

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

So moment is behaving correctly. You should focus instead on your rest API and make sure it's correctly emitting UTC and not a local time value.

Also, if you just want the date portion, then don't use .toISOString . Instead, use .format , such as:

moment.utc(1387843200, 'X').format('YYYY-MM-DD')

You can 'make up' your own format. Any strings that need to be copied as-is (not interpolated) should be contained within brackets.

So in your situation, this should work:

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

After adjusting the onChange functionality, like

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

The onChange function can look like this:

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

It seems the onChange value comes in as Unix ms timestamp (x) instead of Unix timestamp (X) in case that is ever a confusion.

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

Don't 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]')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM