[开发|前端] dayjs获取月份和季度起始时间

  1. 获取季度起始日期
    要获取季度的起始日期,可以使用Day.js的startOf方法结合quarter单位来实现。

下面是一个示例代码,演示如何使用Day.js获取当前季度的起始日期:

const dayjs = require('dayjs');
require('dayjs/plugin/quarterOfYear');
dayjs.extend(require('dayjs/plugin/quarterOfYear'));

// 获取当前季度的起始日期
const currentQuarterStart = dayjs().startOf('quarter');

console.log(currentQuarterStart.format('YYYY-MM-DD'));

在这个示例中,我们首先导入了Day.js库和quarterOfYear插件,该插件添加了用于季度操作的方法。然后,我们使用dayjs()创建了一个Day.js对象,表示当前日期和时间。接下来,我们使用startOf方法,传递quarter作为参数,以获取当前季度的起始日期。最后,我们使用format方法将结果格式化为’YYYY-MM-DD’形式,并进行输出。

  1. 获取月份起始日期
    要获取月份的起始日期,可以使用Day.jsstartOf方法结合month单位来实现。
    以下是一个示例代码,演示如何使用Day.js获取当前月份的起始日期:
const dayjs = require('dayjs');

// 获取当前月份的起始日期
const currentMonthStart = dayjs().startOf('month');

console.log(currentMonthStart.format('YYYY-MM-DD'));

在这个示例中,我们使用dayjs()创建了一个Day.js对象,表示当前日期和时间。然后,我们使用startOf方法,传递month作为参数,以获取当前月份的起始日期。最后,我们使用format方法将结果格式化为’YYYY-MM-DD’形式,并进行输出。

  1. 获取年度起始日期
    要使用 Day.js 获取年度的起始日期,可以使用 startOf 方法结合 ‘year’ 单位来实现。
    以下是一个示例代码,演示如何使用 Day.js 获取当前年度的起始日期:
const dayjs = require('dayjs');

// 获取当前年度的起始日期
const currentYearStart = dayjs().startOf('year');

console.log(currentYearStart.format('YYYY-MM-DD'));

猜你喜欢

转载自blog.csdn.net/macaiyun0629/article/details/131223900