开发者

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)


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


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"


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


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


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

would give 10-01-2011

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜