如何在 JavaScript 中将日期增加一个月?接收未捕获的类型错误
How to increment date by one month in JavaScript? Receiving Uncaught TypeError
我有一个 Bootstrap datepicker
,其中选择了日期。单击按钮 New Date
后,在 datepicker
中选择的 date
应该增加一个月。
我有以下代码:
function getNewDate(){
var date = new Date();
date = $("#selectedDate").val();
// alert(date);
var newDate = new Date();
newDate = date.setMonth(date.getMonth()+1);
// alert(newDate);
}
但是,在执行此操作时,出现以下错误:
Uncaught TypeError: date.getMonth is not a function
我哪里错了?
jQuery .val()
returns 一个字符串,然后必须对其进行解析。下面的代码假定它实际上是可以解析的格式。最好使用 yyyy-mm-dd
.
此外,重要的是要知道 date.setMonth(...)
会更改基础 date
对象。
另请注意,'impossible dates' 会滚动到下个月,例如在 2018-10-31
的源日期上执行 date.setMonth(11)
将导致 'impossible date' 2018-11-31
,然后变为 2018-12-01
.
演示:
function getNewDate() {
var str = $("#selectedDate").val(); // get string
console.log(str);
var date = new Date(str); // parse string
console.log(date);
date.setMonth(date.getMonth() + 1); // change date
console.log(date);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="selectedDate" value="2018-12-20" />
<button onclick="getNewDate()">Add month</button>
我有一个 Bootstrap datepicker
,其中选择了日期。单击按钮 New Date
后,在 datepicker
中选择的 date
应该增加一个月。
我有以下代码:
function getNewDate(){
var date = new Date();
date = $("#selectedDate").val();
// alert(date);
var newDate = new Date();
newDate = date.setMonth(date.getMonth()+1);
// alert(newDate);
}
但是,在执行此操作时,出现以下错误:
Uncaught TypeError: date.getMonth is not a function
我哪里错了?
jQuery .val()
returns 一个字符串,然后必须对其进行解析。下面的代码假定它实际上是可以解析的格式。最好使用 yyyy-mm-dd
.
此外,重要的是要知道 date.setMonth(...)
会更改基础 date
对象。
另请注意,'impossible dates' 会滚动到下个月,例如在 2018-10-31
的源日期上执行 date.setMonth(11)
将导致 'impossible date' 2018-11-31
,然后变为 2018-12-01
.
演示:
function getNewDate() {
var str = $("#selectedDate").val(); // get string
console.log(str);
var date = new Date(str); // parse string
console.log(date);
date.setMonth(date.getMonth() + 1); // change date
console.log(date);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="selectedDate" value="2018-12-20" />
<button onclick="getNewDate()">Add month</button>