0

I am uploading a date time to a field on a dynamics form, and the form needs to receive a UTC date time. If I do something like this:

new Date(new Date().toISOString()) 

If i console.log the date it shows as: Fri Dec 18 2020 14:27:39 GMT-0500 (Eastern Standard Time)

I want the object to print as the UTC time with UTC specified as the time zone, otherwise the form (expecting a date object) keeps uploading as the EST time.

Jacob Alley
  • 767
  • 8
  • 34

3 Answers3

0

Use Date.UTC

const utcDate1 = new Date(Date.UTC(96, 1, 2, 3, 4, 5));

Docs

Alex Mckay
  • 3,463
  • 16
  • 27
0

Edit: As another user mentioned, you must use Date.UTC.

var date = new Date(Date())

var utcDate = date.toUTCString();

console.log(utcDate)
Aib Syed
  • 3,118
  • 2
  • 19
  • 30
  • this just gets me a string of the day of the month in UTC (so for today it would be 18) ... look at the output of your snippet, clearly not what i am looking for although i do appreciate you taking time out of your day to try – Jacob Alley Dec 18 '20 at 19:40
  • Apologies, please see my updated snippet. – Aib Syed Dec 18 '20 at 19:59
0

Date objects are just an offset in milliseconds from the ECMAScript epoch, 1970-01-01T00:00:00Z. They do not have a timezone. When you stringify the object you get a timestamp that depends on the method used.

Most methods (e.g. toString) use the host settings for timezone and offset and produce timestamps based on those settings.

If you want an ISO 8601 compliant string with zero offset, the use toISOString or toUTCString depending on the format you want:

let d = new Date();
console.log(`local time : ${d.toString()}`);
console.log(`toISOString: ${d.toISOString()}`);
console.log(`toUTCString: ${d.toUTCString()}`);

See How to format a JavaScript date.

In your code, the expression:

new Date(new Date().toISOString()) 

firstly creates a Date object for the current moment in time, then generates a timestamp per the toISOString method. That is then parsed back into a Date object, so the result is identical to:

new Date();
RobG
  • 142,382
  • 31
  • 172
  • 209