coure2011
coure2011

Reputation: 42444

javascript formatted date

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)

Upvotes: 3

Views: 2771

Answers (5)

user113716
user113716

Reputation: 322492

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"

Upvotes: 2

Stephen
Stephen

Reputation: 18917

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();

Upvotes: 0

RoToRa
RoToRa

Reputation: 38400

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();

Upvotes: 1

Sebastiaan
Sebastiaan

Reputation: 432

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

would give 10-01-2011

Upvotes: -1

gabel
gabel

Reputation: 512

var now = new Date();
alert((now .getMonth() < 9 ? '0' : '') + (now .getMonth() + 1))

Upvotes: 4

Related Questions