用js 获取 今日年月日时间 昨日年月日时间 当前年月 上个月年月
时间: 2024-05-04 12:17:09 浏览: 86
js获取当前年月日-YYYYmmDD格式的实现代码
可以使用 JavaScript 的 Date() 对象来获取日期和时间。以下是获取今日年月日时间的代码:
```javascript
let today = new Date();
let year = today.getFullYear();
let month = today.getMonth() + 1;
let day = today.getDate();
let todayStr = year + '-' + month + '-' + day;
console.log(todayStr); // 输出格式为: 2022-10-14
```
获取昨日年月日时间可以通过减去一天的毫秒数来实现:
```javascript
let yesterday = new Date();
yesterday.setDate(yesterday.getDate() - 1);
let year = yesterday.getFullYear();
let month = yesterday.getMonth() + 1;
let day = yesterday.getDate();
let yesterdayStr = year + '-' + month + '-' + day;
console.log(yesterdayStr); // 输出格式为: 2022-10-13
```
获取当前年月可以使用类似获取今日年月日时间的代码:
```javascript
let today = new Date();
let year = today.getFullYear();
let month = today.getMonth() + 1;
let currentMonthStr = year + '-' + month;
console.log(currentMonthStr); // 输出格式为: 2022-10
```
获取上个月年月可以通过减去一个月的毫秒数来实现:
```javascript
let today = new Date();
today.setMonth(today.getMonth() - 1);
let year = today.getFullYear();
let month = today.getMonth() + 1;
let lastMonthStr = year + '-' + month;
console.log(lastMonthStr); // 输出格式为: 2022-09
```
阅读全文