JavaScript wrong timestamp formatting

Viewed 80

I'm currently trying to format a timestamp in JavaScript. Sadly, the result is a bit strange. This is the date I'm trying to format:

Thu May 23 2019 17:34:18 GMT+0200 (Mitteleuropäische Sommerzeit)

And this is how it should looks like after formatting it:

23.05.2019

This is my code:

j = myDateString;
console.log(j.getUTCDate() + "." + j.getUTCMonth() + "." + j.getUTCFullYear());

But when I run my code, this is the result:

23.4.2019

2 Answers

getUTCMonth() starts from 0 (January), fix it by adding one.

console.log(j.getUTCDate() + "." + (j.getUTCMonth() + 1) + "." + j.getUTCFullYear());

Firstly, the month is off. January is 0, december is 11, so add 1 to the month. Secondly, you need a function that pads 0s to the left. Luckily, javascript comes with that.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart

'5'.padStart(2,'0') outputs '05', for example

try this:

console.log(j.getUTCDate().toString().padStart(2,'0') + "." + (j.getUTCMonth() + 1).toString().padStart(2,'0') + "." + j.getUTCFullYear());

[edit] this function may not exist in older browsers, but there's a polyfill on the page I linked, and it's easy to implement yourself.

Related