心流logo

使用dayjs,获取上个月,格式:202410 如何获取dayjs的当前时间? dayjs如何获取当前月份的天数? dayjs如何将日期格式化为YYYYMM格式?

获取上个月的时间(格式:202410)

可以使用dayjs().add(-1, 'onth')来获取上个月的第一天,然后使用format('YYYYMM')来格式化日期。

const dayjs = require('dayjs');
const currentDate = dayjs();
const lastMonth = currentDate.add(-1, 'onth').format('YYYYMM');
console.log(lastMonth); // 输出上个月的时间,如 202410

获取dayjs的当前时间

可以通过dayjs().format('YYYY-MM-DD HH:mm:ss')来获取当前时间。

const currentDate = dayjs();
const currentTime = currentDate.format('YYYY-MM-DD HH:mm:ss');
console.log(currentTime); // 输出当前时间,如 2024-10-08 02:00:00

dayjs如何获取当前月份的天数

可以通过dayjs().daysInMonth()来获取当前月份的天数。

const currentDate = dayjs();
const currentMonthDays = currentDate.daysInMonth();
console.log(currentMonthDays); // 输出当前月份的天数,如 31

dayjs如何将日期格式化为YYYYMM格式

可以通过format('YYYYMM')来将日期格式化为YYYYMM格式。

const currentDate = dayjs();
const formattedDate = currentDate.format('YYYYMM');
console.log(formattedDate); // 输出格式化为YYYYMM的日期,如 202410