Scott Scott - 1 year ago 51
Javascript Question

Ignore/don't convert timezone?

My page was working fine and displaying dates and times as expected until I had to add

new Date()
to avoid the  deprecation warning. Now my date is 5 hours off what it should be.

enter image description here

How can I fix this?
should both be 12:14:26 and, in this instance, fn should be "Seconds ago".

Here is the full code:

var k = key;
var v = obj[key];
var vd = Date.parse(obj[key]));
if (moment(vd).isValid()) {
var fn = moment(vd).fromNow();
v = fn;
return {
name: k,
value: v

I tried the following based on this post, but it brought back the momentjs deprecation warning:

var vd = new Date(Date.parse(obj[key])).toUTCString();

(and still didn't work)


Threaded comments would be cool

What happens if you just run
? Should work. – Maggie Pint

It does work, but I get the deprecation warning.

I just looked closer. The format of V is ISO8601 with offset, so you shouldn't be getting a deprecation if you just call
. If you are, try
moment(v, moment.ISO_8601)
Maggie Pint

Again, works, but I still get the deprecation warning.

instead of
var vd = new Date(Date.parse(obj[key])).toUTCString();
did you try
var vd = new Date(Date.parse(obj[key])).toISOString();
? or even simplier
var vd = Date.parse(obj[key])

it outputs "Invalid Date".
var vd = Date.parse(obj[key])
Is what I had originally, it works as expected but I get the warning.

Your v string appears to use ISO8601 format already? Maybe append the Z, or ask moment to recognise it automatically as UTC when timezone info is missing – Bergi

I just tried
var vd = new Date(Date.parse(obj[key] + "Z"));
and it works!

Answer Source

In your example, you're passing a value for v as an ISO8601 string without any offset specified. It is ambiguous as to what point in time you are actually talking about.

Because of changes in the ECMAScript specification, the value will be interpreted as UTC by some browsers, and as local time by others.

The way to avoid this ambiguity is to not use the date constructor. Anywhere you have new Date or Date.parse, you're introducing potential differences in behavior. Just use moment's own parser, and be specific as to your intent.

// your input
var v = "2016-09-14T12:14:26.149";

// pick only one of these:
var m = moment(v);    // input is local time
var m = moment.utc(v) // input is UTC

// then proceed as normal
if (m.isValid()) {
  var fn = m.fromNow();
  // etc.

If the input is in some other time zone, or has some other specific fixed offset from UTC, then you have various other options for constructing the moment object. But really, don't rely on the Date object to do the parsing. That's the whole point of the deprecation message.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download