Home > other >  How to Format Date to Complete YYYY-MM-DD-HH-MM-SS
How to Format Date to Complete YYYY-MM-DD-HH-MM-SS

Time:04-23

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);

CodePudding user response:

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.

CodePudding user response:

Try this

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

CodePudding user response:

you can do that...

let now = new Date()

now.setMinutes(now.getMinutes() - now.getTimezoneOffset())

console.log(now.toISOString().slice(0,19).replace(/[T:]/g, '-'));

  • Related