Javascript Date Help

Hi,

basically I want to display todays date in reverse to form a invoice number
this code taken form w3schools will display the year

<script>
var d = new Date();
document.getElementById("demo").innerHTML = d.getFullYear();
</script>

but I need to add month and day without spaces with I believe
d.getDate()
and
d.getMonth()

how do I do this

cheers

Comments

  • var d = new Date().toISOString().slice(0,10);
    d = d.replace(/-/g, '');

    document.getElementById('demo').innerHTML = d;

    Probably a million other ways too.

    • nice, thankyou. unfortunately it displays yesterdays date. :(

      • +2

        Sorry.. change it to:

        var d = (new Date(Date.now() - (new Date().getTimezoneOffset() * 60000))).toISOString().slice(0,10);

        • Excellent thankyou, works perfect.

  • +1

    Watch out that the getMonth and getDate methods on date are 0-indexed i.e. January is 0 not 1.

    Also in future I highly recommend searching StackOverflow.

    • thanks, I did check out stackoverflow before posting, but unfortunately me playing with js is like a 3 year old trying to stick their fingers into a power point.

      • +1

        JavaScript in the browser is sandboxed, so there's a limit to how much damage you can do. Unless you're writing JS for Node. Then you can break things!

        If you're not allowed to use momentjs (the cure for all date woes in JS) then if you want YYYYMMDD I would do what sebastian.i did in this answer.

Login or Join to leave a comment