Home > Enterprise >  What is JavaScript's default Date format?
What is JavaScript's default Date format?

Time:07-07

What is the name of this format?

Wed Jul 06 2022 14:42:13 GMT-0400 (Eastern Daylight Time)

This format is the default format that is output "Independent of input format" from new Date().

How do you turn a date into that format using Moment.js?

  • Example: 2022-07-15T00:00:00.000Z or 2015-03-25
console.log(moment(new Date()).toISOString());
// 2022-07-06T19:08:36.670Z

console.log(moment(new Date()).toString());
// Wed Jul 06 2022 15:08:36 GMT-0400

console.log(new Date());
// Wed Jul 06 2022 15:08:36 GMT-0400 (Eastern Daylight Time)

console.log(new Date().toString());
// Wed Jul 06 2022 15:08:36 GMT-0400 (Eastern Daylight Time)

You can see that moment(new Date()).toISOString() and moment(new Date()).toString() DO NOT output that same format as the default JS format.

  • moment(new Date()).toString() is close, but is still missing the (Eastern Daylight Time) which is part of the default.

CodePudding user response:

What is the name of this format?

It's not ISO, it's a format specified in ECMA-262, read more here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toString

To convert it to ISO use date.toISOString()

Btw. don't use w3schools.com this website has major errors

How do you turn a date into that format using Moment.js?

  1. ISO: moment(new Date()).toISOString()
  2. 2015-03-25: moment(new Date()).format('yyyy-MM-dd')
  3. ECMA-262: moment(new Date()).toDate().toString()

P.S. I would consider using a different library as moment.js isn't getting updates anymore, but if you don't have a choice it's fine.

CodePudding user response:

Answer:

console.log(moment(new Date()).toDate());

That was way harder to find than it should have been.

console.log(moment(new Date()).toDate());
// Wed Jul 06 2022 15:25:52 GMT-0400 (Eastern Daylight Time)

console.log(new Date());
// Wed Jul 06 2022 15:25:52 GMT-0400 (Eastern Daylight Time)

console.log(new Date().toString());
// Wed Jul 06 2022 15:25:52 GMT-0400 (Eastern Daylight Time)


  • Related