可以使用JavaScript中的Date对象来实现。具体用法如下:
```javascript
var now = new Date(); // 获取当前时间
var oneMonthAgo = new Date(now.getFullYear(), now.getMonth() - 1, now.getDate()); // 获取一个月前的日期
var threeMonthsAgo = new Date(now.getFullYear(), now.getMonth() - 3, now.getDate()); // 获取三个月前的日期
// 格式化日期字符串
function formatDate(date) {
var year = date.getFullYear();
var month = date.getMonth() + 1;
var day = date.getDate();
return year + '-' + (month < 10 ? '0' + month : month) + '-' + (day < 10 ? '0' + day : day);
}
var oneMonthAgoStr = formatDate(oneMonthAgo);
var threeMonthsAgoStr = formatDate(threeMonthsAgo);
console.log(oneMonthAgoStr); // 输出:2022-01-22
console.log(threeMonthsAgoStr); // 输出:2021-11-22
```
以上代码中,我们首先通过new Date()获取了当前时间,然后分别使用Date对象的构造函数来获取一个月前和三个月前的日期。接着,我们定义了一个formatDate函数来将日期对象格式化成指定格式的日期字符串,并将这些日期字符串输出到控制台。
需要注意的是,在获取一个月前和三个月前的日期时,我们使用了Date对象的构造函数,并传入了年、月、日等参数。由于月份从0开始,因此在获取一个月前和三个月前的日期时,需要对月份进行相应的调整。另外,在拼接日期字符串时,为了保证格式的统一,我们对月份、日期进行了补零操作。