2

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

Mr. Jo
  • 3,961
  • 1
  • 22
  • 54
  • Strings don't have those methods, so you can't be dealing with a string, you must be dealing with a Date object. Do you really want UTC values, or local? – RobG Jun 26 '19 at 11:52
  • @RobG Please remove the duplicate because it's not a duplicate. A duplicate is an exact question which has the same result. As you can see at your duplicate question, the outgoing is completely different. – Mr. Jo Jun 26 '19 at 12:21

2 Answers2

5

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

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

devgianlu
  • 1,484
  • 10
  • 21
  • 1
    Additionally, if you want zeropadded months you can use `padStart` like so: `(j.getUTCMonth() + 1).toString().padStart(2, '0')` – Phillip Jun 26 '19 at 11:30
3

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.

TKoL
  • 10,782
  • 1
  • 26
  • 50