3

Let say date current date is 10 Jan 2011. When I get date using js code

var now = new Date();
var currentDate = now.getDate() + '-' + (now.getMonth() + 1) + '-' + now.getFullYear();

It reutrns "10-1-2011"
but I want "10-01-2011" (2 places format)

5 Answers 5

4
var now = new Date();
alert((now .getMonth() < 9 ? '0' : '') + (now .getMonth() + 1))
Sign up to request clarification or add additional context in comments.

Comments

2

Here's a nice short way:

('0' + (now.getMonth() + 1)).slice(-2)

So:

var currentDate = now.getDate() + '-' + ('0' + (now.getMonth() + 1)).slice(-2) + '-' + now.getFullYear();
  • (now.getMonth() + 1) adjust the month

  • '0' + prepends a "0" resulting in "01" or "012" for example

  • .slice(-2) slice off the last 2 characters resulting in "01" or "12"

Comments

1
function leftPad(text, length, padding) {
  padding = padding || "0";
  text = text + "";
  var diff = length - text.length;
  if (diff > 0)
     for (;diff--;) text = padding + text;
  return text;
}

var now = new Date();

var currentDate = leftPad(now.getDate(), 2) + '-' + leftPad(now.getMonth() + 1, 2js) + '-' + now.getFullYear();

Comments

0

the quick and nasty method:

var now = new Date();
var month = now.getMonth() + 1;
var currentDate = now.getDate() + '-' + (month < 10 ? '0' + month : month) + '-' + now.getFullYear();

Comments

-1
var now = new Date();
now.format("dd-mm-yyyy");

would give 10-01-2011

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.