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

2
  • 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? Commented Jun 26, 2019 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. Commented Jun 26, 2019 at 12:21

2 Answers 2

5

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

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

Sign up to request clarification or add additional context in comments.

1 Comment

Additionally, if you want zeropadded months you can use padStart like so: (j.getUTCMonth() + 1).toString().padStart(2, '0')
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.