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!
Use the getTime() method to get a UTC timestamp, e.g. new Date(). getTime() . The method returns the number of milliseconds since the Unix Epoch and always uses UTC for time representation. Calling the method from any time zone returns the same UTC timestamp.
A few things you should know about Unix timestamps:Unix timestamps are always based on UTC (otherwise known as GMT). It is illogical to think of a Unix timestamp as being in any particular time zone. Unix timestamps do not account for leap seconds.
In PostgreSQL, we can use the to_timestamp() function to convert a Unix timestamp value to a date/time value. The Unix timestamp (also known as Unix Epoch time, Unix time, or POSIX time) is the number of seconds that have elapsed since 00:00:00 Thursday, 1 January 1970, Coordinated Universal Time (UTC).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With