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)

asked Jan 11, 2011 at 14:33

5 Answers 5

4
var now = new Date();
alert((now .getMonth() < 9 ? '0' : '') + (now .getMonth() + 1))
answered Jan 11, 2011 at 14:39
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"

answered Jan 11, 2011 at 14:58

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();
answered Jan 11, 2011 at 14:42

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();
answered Jan 11, 2011 at 14:52

Comments

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

would give 10-01-2011

answered Jan 11, 2011 at 14:40

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.