Home > Net >  Javascript | Get Current UTC DateTime In DateTime Format - Not String
Javascript | Get Current UTC DateTime In DateTime Format - Not String

Time:12-05

The codes below return current UTC datetime in string format.
But i am looking for a function in javascript that return current utc datetime in datetime format.
It seems there is no such that function in javascript.

var dateTime_now = new Date();
var dateTime_now_utc_str = dateTime_now.toUTCString();
alert(dateTime_now_utc_str);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

.toISOString() is what you want, not .toUTCString()

You already have the Javascript internal DateTime format in the variable dateTime_now. So I think you do want a string output, but not the string Sun, 05 Dec 2021 06:11:15 GMT, because it contains useless strings like Sun and useful, but non-numerical strings like Dec. I am guessing you do want a string output, but containing digits and separators and no words.

var dateTime_now = new Date();
var dateTime_now_utc_str = dateTime_now.toISOString();
console.log(dateTime_now_utc_str);

// Result:      2021-12-05T06:10:54.299Z
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Why?

A detailed explanation of why is given here, by me:

enter image description here

CodePudding user response:

I think it would be better if you use moment js.

  • Related