Jquery / Javascript - Add years to date variable

后端 未结 6 1470
耶瑟儿~
耶瑟儿~ 2021-02-19 06:05

I have a small trouble that would be great to have some help with. I am creating a small form that I want to take a current date formatted \'dd/mm/yyyy\' and add a

6条回答
  •  礼貌的吻别
    2021-02-19 06:36

    I would:

    • put the date in a format that Date.parse can work nicely with (mm/dd/yyyy)
    • add the number of milliseconds in a year times the selected option
    • Reformat the new value to a human-readable format and populate #expires

      var dateArr = $("#startdate").val().split();
      var niceDate = Number(dateArr[1]) + "/" + Number(dateArr[0]) + "/" + Number(dateArr[2]);

      var expDate = Date.parse(niceDate) + 365*24*60*60*1000*Number($("#registerfor").val());

      $("#expires").val(expDate.getMonth()+1 + "/" + expDate.getDate() + "/" + expDate.getFullYear());

    If you need 2-digit days and months for expiration date, you could have extra variables that hold a string version of them and check something like:
    var padMonth = expDate.getMonth()+1;
    if(expDate.getMonth()+1 < 10) padMonth = "0" + Number(expDate.getMonth()+1);

    After which, you would use padMonth in $("#expires").val(...)

提交回复
热议问题