0

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);
SilverLight
  • 19,668
  • 65
  • 192
  • 300

1 Answers1

2

.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

Why?

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

https://stackoverflow.com/a/58347604/7549483

In short, UTC simply means "in the timezone of GMT+0", while ISO is the name of the format yyyy-mm-dd etc. The full name of the date format is ISO 8601.

ProfDFrancis
  • 8,816
  • 1
  • 17
  • 26
  • In that case, I don't understand what you mean by DateTime format. Did you mean Javascript's internal DateTime format? In which case you already have that in the variable `dateTime_now`, don't you? If not, can you give an example of what you mean by DateTime format? – ProfDFrancis Dec 05 '21 at 06:19
  • Have you tried using the `new Intl.DateTimeFormat()` object? – Derek Dec 05 '21 at 06:19
  • 1
    Please don't post images, post text. There really is no reason to post an image of a wikipedia page, it shouldn't be used as a reference anyway. If there is an answer for the question already, then close it as a duplicate. – RobG Dec 06 '21 at 08:48