3

Possible Duplicate:
How to get current date in JavaScript

I need to get todays date in the format yyyymmdd using JavaScript.

I've used the following code:

var d = new Date();
d.getFullYear()+ '' +((d.getMonth()+1)) + '' + d.getDate();

But the month and date are returned in single digits, does someone know how to do this?

1
  • @NimChimpsky Agreed. Maybe not an exact duplicate but the top answer certainly answers the question :) Commented Jul 4, 2012 at 14:48

2 Answers 2

1
        var d = new Date();
        var df = d.getFullYear()
            + ('0' + String(d.getMonth()+1)).substr(-2)
            + ('0' + String(d.getDate())).substr(-2);
        alert(df);
Sign up to request clarification or add additional context in comments.

Comments

1

You can do this following way. But you need to write one extra function as below:

function getTwoDigit(number) {       
    return (number < 10 ? '0' : '') + number       
}

Now you can use that function on your original code.

var d = new Date();d.getFullYear()+ '' +(getTwoDigit(d.getMonth()+1)) + '' + getTwoDigit(d.getDate());

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.