0

I am absolutely new to Javascript. I am trying to get a certain format for a date I need inserted. Essentially, I want it to look like mm/dd/yy but I do not want leading zeros when there is a single digit month or date. Is this possible? I tried the code here but it gives me leading zeros and a four digit year.

Thank you all in advance.

  • You are on the right track, especially with [this answer](https://stackoverflow.com/a/64269468/1871033). Read the linked documentation, you'll find [a lot of options described there](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat). In your particular case you'd use `2-digit` for year and `numeric` for month and day. – CherryDT Jan 11 '22 at 17:05
  • Wonder if my answer solve your problem? – James Jan 21 '22 at 21:34

2 Answers2

0

Try this, it does what you want:

let today = new Date();
const day = String(today.getDate())
const month = String(today.getMonth() + 1); // January is counted as 0
let year = today.getFullYear();

year = `${year}`.split("").splice(2,3).join("")

today = `${day}/${month}/${year}`;
document.write(today);
iammithani
  • 108
  • 2
  • 10
0

I think you are looking at the top votes answer from the question you are looking at.

In the answer, they use the padstart() to insert 0 for single day.

The padStart() method pads the current string with another string (multiple times, if needed) until the resulting string reaches the given length. The padding is applied from the start of the current string.

The simplest solution is to just remove the two padStart from that answer.

var today = new Date();
var dd = String(today.getDate())
var mm = String(today.getMonth() + 1); //January is 0!
var yyyy = today.getFullYear();

today = mm + '/' + dd + '/' + yyyy;
document.write(today);
James
  • 2,732
  • 2
  • 5
  • 28