Skip to content
大纲

获取指定日期的相应模式

语法

js
import { getDateOf } from 'warbler-js';
const result = getDateOf(mode, date);

参数

  • mode (String) : 获取版本号的模式,支持以下值,默认为 day
    daymonthquarterhalfYearyear
    季度半年
  • date (String) : 指定日期,可传参数同 new Date(),并且支持 yyyy-mm-dd格式 ,不传默认获取当天。

返回值

String : 返回指定模式的日期字符串。

源码

js
const getDateOf = (mode, date) => {
  const myData = date ? new Date(typeof date === 'string' && date.includes('-') ? date.replace(/-/g, '/') : date) : new Date();
  const year = myData.getFullYear();
  const month = myData.getMonth() + 1;
  const day = myData.getDate();
  const quarter = Math.floor((month + 2) / 3);
  const halfYear = Math.floor((month + 5) / 6);
  switch (mode) {
    case 'day':
      return `${year}-${month}-${day}`;
    case 'month':
      return `${year}-${month}`;
    case 'quarter':
      return `${year}-Q${quarter}`;
    case 'halfYear':
      return `${year}-H${halfYear}`;
    case 'year':
      return `${year}`;
    default:
      return `${year}-${month}-${day}`;
  }
};

例子

js
import { getDateOf } from 'warbler-js';
// 测试当前日期 (2023-09-22)

// 默认获取当前日
console.log(getDateOf()); // => 2023-9-22
// 获取当前日
console.log(getDateOf('day')); // => 2023-9-22
// 获取当前月
console.log(getDateOf('month')); // => 2023-9
// 获取当前季度
console.log(getDateOf('quarter')); // => 2023-Q3
// 获取当前半年
console.log(getDateOf('halfYear')); // => 2023-H2
// 获取当前年
console.log(getDateOf('year')); // => 2023

// 测试指定日期

// 获取当前日
console.log(getDateOf('day', '2025-03-09')); // => 2025-3-9
// 获取当前月
console.log(getDateOf('month', '2025-03-09')); // => 2025-3
// 获取当前季度
console.log(getDateOf('quarter', '2025-03-09')); // => 2025-Q1
// 获取当前半年
console.log(getDateOf('halfYear', '2025-03-09')); // => 2025-Q1
// 获取当前年
console.log(getDateOf('year', '2025-03-09')); // => 2025

添加版本

1.2.4

Released under the MIT License.