javascript - 如何使用javascript为给定日期添加年份

标签 javascript date

i need to add a year to given date. I have try this code

<script>
  function get_expir(){ 
     regDate = document.getElementById('txt1').value;         

     var da = new Date(regDate);
     da.setFullYear(da.getFullYear()+1, da.getMonth()+1);
     document.form1.txt2.value = da.getFullYear()+ '-'+ da.getMonth()+ '-'+ da.getDate();  
  }
</script

if the user input is '2012-02-29' then the output will comes '2013-2-29'. Blockquote

最佳答案

试试这个:

var da = new Date(regDate);

da.setFullYear(da.getFullYear()+1);

var curr_date =  ("0" + (da.getDate())).slice(-2)
var curr_month = ("0" + (da.getMonth() + 1)).slice(-2)
var curr_year = da.getFullYear();

document.form1.txt2.value = curr_date + "-" + curr_month + "-" + curr_year;

关于javascript - 如何使用javascript为给定日期添加年份,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28558380/

相关文章:

javascript - 如何将div设置为背景?

javascript - Google Maps API,在不使用坐标的情况下在国家/地区放置标记

Python Pandas 不正确的日期计数

php - 两个日期内有多少周

javascript - 'Currying'是什么?

javascript - 未捕获的类型错误 : Cannot read property 'event' of undefined using Laravel 5. 3

javascript - Mongoose 在循环内获取多个对象

python - 如何将特定月份值与 pandas 数据框中的日期相加?

MySQL 按月选择对所有月份返回 NULL

java - 将 Java SQL 日期从 yyyy-MM-dd 格式转换为 dd MMMM yyyy 格式的最佳方法