Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/469.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/71.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
JavaScript/jQuery:格式化日期计算结果的最佳方式_Javascript_Jquery_Date_Date Format_Date Arithmetic - Fatal编程技术网

JavaScript/jQuery:格式化日期计算结果的最佳方式

JavaScript/jQuery:格式化日期计算结果的最佳方式,javascript,jquery,date,date-format,date-arithmetic,Javascript,Jquery,Date,Date Format,Date Arithmetic,我正在使用以下函数向给定的日期输入添加天数(格式:yyyy-mm-dd) 这很好,但在需要时不会添加前导零,例如,它返回2013-11-1,而不是我需要的2013-11-01 将输出格式化为yyyy-mm-dd-jQuery的最佳/最短方式是什么? function calcTargetDate() { var timeFrame = 7; var targetDate = new Date( document.getElementById('date1').value

我正在使用以下函数向给定的日期输入添加天数(格式:yyyy-mm-dd)

这很好,但在需要时不会添加前导零,例如,它返回2013-11-1,而不是我需要的2013-11-01

将输出格式化为yyyy-mm-dd-jQuery的最佳/最短方式是什么?

 function calcTargetDate()
 {
     var timeFrame = 7;
     var targetDate = new Date( document.getElementById('date1').value );

     targetDate.setDate( targetDate.getDate() + parseInt(timeFrame) );
     document.getElementById('date2').value = ( targetDate.getFullYear() + '-' + (targetDate.getMonth() + 1) + '-' + targetDate.getDate() );
 }

非常感谢您在这方面的帮助,Tim是否包括一个lib选项?您可以通过以下方式轻松做到这一点:

var targetDate = moment( document.getElementById('date1').value );
targetDate.add('days', timeFrame); //or whatever unit your timeframe value is if not days
document.getElementById('date2').value = targetDate.format("YYYY-MM-DD");

对于任何日期格式,我总是使用


jQuery是一个DOM操作库。这在这里没有用。谢谢,巴布洛-这正是我需要的。这也很棒-非常感谢。我看了这个,决定用它。真是太棒了,非常感谢!
 var myDate = new Date(2013, 10, 1); // remember month zero-indexed in javascript
 console.log(myDate);
 console.log(moment(myDate).format('YYYY-MM-D'));