开发者

Add 30 days to date (mm/dd/yyyy) then return string (mm/dd/yyyy)

I have the function below which takes a string from the datepicker and turns it into a date object so I can add 30 days to it. From there I am trying to return the new date as a string with 30 days added to it, in the format of (mm/dd/yy).

When the first alert fires it correctly adds 30 days to the selected date and shows this for selcted date as "05/03/2011":

Thu Jun 02 2011 00:00:00 GMT+0100 (GMT Daylight Time)

The second alert shows

5/2/2011

Seems I can't correctly format the date and take "05/03/2011" and return "06/02/2011". I could just do month + 1, but could do with some help please and show me what I am doing wrong.

  $('#sign_date').datepicker({
      onSelect: function(dateText, inst) { 

          var d = new Date(dateText);
          d.setDate(d.getDate() + 30);

          alert(d);

          var date = d.getDate();
          var month = d.getMonth();
          var year = d.getFullYear();

          alert(month+'/'+date +'/'+year)

      }
  });
开发者_Python百科

Also I think they way I am doing it will show days and month as e.g. Jan = 1 and 1st = 1 and I would like it to be Jan = 01 and 1st = 01

Thanks


For leading zeros:

// add leading zero if the length equals 1
if (month < 10) month = "0" + month;
if (day < 10)   day   = "0" + day;

Be sure to add 1 to your month prior to using this code, too, since getMonth() returns a 0 for January, and so on:

 var month = d.getMonth() + 1;


Surprise, surprise... The getMonth() method returns the month in the range 0..11.


Answer from Kelly works to me

Just changed this

if(month<9) month = "0"+(month+1);
if(date<10) day = "0"+date;
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜