0

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);
Suffii
  • 5,694
  • 15
  • 55
  • 92
  • You can use the `getHours`, `getMinutes`, and `getSeconds` methods. – kelsny Apr 22 '22 at 20:34
  • Does this answer your question? [How do I format a date in JavaScript?](https://stackoverflow.com/questions/3552461/how-do-i-format-a-date-in-javascript) – Tibrogargan Apr 22 '22 at 22:06
  • [What is the "right" JSON date format?](https://stackoverflow.com/questions/10286204/what-is-the-right-json-date-format?r=SearchResults&s=2|416.7401) – Tibrogargan Apr 22 '22 at 22:07
  • [Where can I find documentation on formatting a date in JavaScript?](https://stackoverflow.com/questions/1056728/where-can-i-find-documentation-on-formatting-a-date-in-javascript?r=SearchResults&s=3|411.1889) – Tibrogargan Apr 22 '22 at 22:08
  • [Format JavaScript date as yyyy-mm-dd](https://stackoverflow.com/questions/23593052/format-javascript-date-as-yyyy-mm-dd?r=SearchResults&s=5|280.1472) – Tibrogargan Apr 22 '22 at 22:09

2 Answers2

0

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.
Nathan Mills
  • 2,243
  • 2
  • 9
  • 15
0

Try this

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