javascript获取我选中日期的上一个月的时间
时间: 2024-02-24 08:59:38 浏览: 18
可以使用内置的 `Date` 对象和一些简单的算法来获取你选中日期的上一个月的时间。以下是一个获取你选中日期的上一个月的时间的示例:
HTML 代码:
```
<input type="date" id="myDate">
<button onclick="getLastMonth()">获取上一个月的时间</button>
```
JavaScript 代码:
```
function getLastMonth() {
var selectedDate = new Date(document.getElementById("myDate").value);
var lastMonth = new Date(selectedDate.getFullYear(), selectedDate.getMonth() - 1, selectedDate.getDate());
var date = lastMonth.getFullYear()+'-'+(lastMonth.getMonth()+1)+'-'+lastMonth.getDate();
console.log(date);
}
```
在上面的示例中,`getLastMonth()` 函数获取选中日期的值,并将其传递给 `Date` 对象来创建一个新的日期对象。然后使用 `getFullYear()`、`getMonth()` 和 `getDate()` 方法获取年、月和日的值,并将它们组合成一个字符串,以便在控制台中打印出来。
注意:`getMonth()` 方法返回的月份值是从 0 开始的,因此需要在值上减去 1 才能获取正确的月份值。在这个例子中,我们使用 `selectedDate.getMonth() - 1` 来获取上一个月的月份值。同时,我们创建了一个新的 `Date` 对象 `lastMonth`,将其月份设置为上一个月。