开发者

Ajax get Date in dd/mm/yyyy format

var 开发者_如何学Pythond = new Date();
    var today_date = d.getDate() + '/' + month_name[d.getMonth()] + '/' + d.getFullYear();

This is how I am getting a date. It works with a slight problem. For todays date 7th of June 2011 it returns 7/11/2011, what i want it to return is 07/11/2011?

Anyone know how?


Well, you could simply check the length of d.getDate()and if it's 1 then you add a zero at the beginning. But you would like to take a look at format() to format your dates?


Like so:

("0"+1).slice(-2);  // returns 01
("0"+10).slice(-2); // returns 10

Complete example:

var d = new Date(2011,1,1); // 1-Feb-2011
var today_date =
    ("0" + d.getDate()).slice(-2) + "/" +
    ("0" + (d.getMonth() + 1)).slice(-2) + "/" + 
    d.getFullYear();
// 01/02/2011


Try this (http://blog.stevenlevithan.com/archives/date-time-format):

var d = new Date();
d.format("dd/mm/yyyy"); 


Try this, this is more understandable.:

  var currentTime = new Date();
  var day = currentTime.getDate();
  var month = currentTime.getMonth() + 1;
  var year = currentTime.getFullYear();

  if (day < 10){
  day = "0" + day;
  }

  if (month < 10){
  month = "0" + month;
  }

  var today_date = day + "/" + month + "/" + year;
  document.write(today_date.toString());

And result is :

07/05/2011

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜