'How to Format Date to Complete YYYY-MM-DD-HH-MM-SS

Can you please take a look at this code and let me know how I can get the output in YYYY-MM-DD-HH-MM-SS format?

As you can see what I am getting now is 2022-04-22 which is YYYY-MM-DD

const d = new Date();
var dStr = new Date(d.getTime() - (d.getTimezoneOffset() * 60000)).toISOString().split("T")[0];

console.log(dStr);


Solution 1:[1]

You can get YYYY-MM-DD-HH-MM-SS format like this:

new Date(d.getTime() - (d.getTimezoneOffset() * 60000)).toISOString().split(".")[0].replace(/[T:]/g, '-')

Explanation:

  • .split(".")[0] removes the dot near the end and everything after it.
  • .replace(/[T:]/g, '-') changes the T and the colons (:) to dashes.

Solution 2:[2]

Try this

const value = new Date().toLocaleString('sv-SE').replace(/[\s\:]/g, '-')
console.log(value)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nathan Mills
Solution 2 Shinigami