js获取当前时间和前三个月时间,避免跨年年份不减
时间: 2023-05-14 19:06:56 浏览: 70
可以使用JavaScript中的Date对象来获取当前时间和前三个月的时间,代码如下:
```
// 获取当前时间
var currentDate = new Date();
// 获取前三个月的时间
var threeMonthsAgo = new Date();
threeMonthsAgo.setMonth(currentDate.getMonth() - 3);
// 格式化时间
var currentYear = currentDate.getFullYear();
var currentMonth = currentDate.getMonth() + 1;
var currentDay = currentDate.getDate();
var threeMonthsAgoYear = threeMonthsAgo.getFullYear();
var threeMonthsAgoMonth = threeMonthsAgo.getMonth() + 1;
var threeMonthsAgoDay = threeMonthsAgo.getDate();
// 避免跨年年份不减
if (currentMonth < 3) {
currentYear--;
}
if (threeMonthsAgoMonth < 3) {
threeMonthsAgoYear--;
}
// 输出结果
console.log("当前时间:" + currentYear + "-" + currentMonth + "-" + currentDay);
console.log("前三个月时间:" + threeMonthsAgoYear + "-" + threeMonthsAgoMonth + "-" + threeMonthsAgoDay);
```
注意,这里使用了setMonth()方法来设置月份,如果设置的月份小于0或大于11,Date对象会自动调整年份和月份。因此,在避免跨年年份不减的时候,需要判断当前月份是否小于3。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)