DayJs
yuhuo2022-11-21开发库工具库
参考链接
解析
import dayjs from "dayjs";
import objectSupport from "dayjs/plugin/objectSupport";
import arraySupport from "dayjs/plugin/arraySupport";
dayjs.extend(objectSupport);
dayjs.extend(arraySupport);
// 默认当前时间
let day1 = dayjs();
// 传入Date对象
let day2 = dayjs(new Date("2021/01/02"));
// 传入时间字符串
let day3 = dayjs("2021/01/03 12:13:14"); // 默认格式
let day4 = dayjs("01-03-2021", "DD-MM-YYYY"); // 指定格式
// 传入时间戳
let day5 = dayjs(1609733594000); // 毫秒
let day6 = dayjs.unix(1609733594); // 秒
// 传入对象(需要导入objectSupport)
let day7 = (dayjs as any)({
year: 2021, // 简写 y
month: 0, // 简写 M(月份从0开始)
date: 5, // 简写 d
hour: 12, // 简写 h
minute: 13, // 简写 m
second: 14, // 简写 s
millisecond: 156, // 简写 ms
});
// 传入数组(需要导入arraySupport)
let day8 = dayjs([2021, 0, 6, 12, 13, 14, 156]);
// 传入dayjs对象
let day9 = dayjs(day);
// 克隆dayjs对象
let day10 = day.clone();
设值
(生成新对象)
import dayjs from "dayjs";
import dayOfYear from "dayjs/plugin/dayOfYear";
import weekOfYear from "dayjs/plugin/weekOfYear";
import quarterOfYear from "dayjs/plugin/quarterOfYear";
dayjs.extend(dayOfYear);
dayjs.extend(weekOfYear);
dayjs.extend(quarterOfYear);
let day = dayjs();
// 通用设值
let day1 = day.set("date", 2);
// 特定设值
let day2 = day.minute(2);
// 设值年份里第几天(需要导入dayOfYear)
let day3 = day.dayOfYear(2);
// 设值年份里第几周(需要导入weekOfYear)
let day4 = day.week(2);
// 设值年份里第几季度(需要导入quarterOfYearr)
let day5 = day.quarter(2);
取值
import dayjs from "dayjs";
import dayOfYear from "dayjs/plugin/dayOfYear";
import weekOfYear from "dayjs/plugin/weekOfYear";
import quarterOfYear from "dayjs/plugin/quarterOfYear";
dayjs.extend(dayOfYear);
dayjs.extend(weekOfYear);
dayjs.extend(quarterOfYear);
let day = dayjs();
// 通用取值
let day1 = day.get("date", 2);
// 特定取值
let day2 = day.minute();
// 取值年份里第几天(需要导入dayOfYear)
let day3 = day.dayOfYear();
// 取值年份里第几周(需要导入weekOfYear)
let day4 = day.week();
// 取值年份里第几季度(需要导入quarterOfYearr)
let day5 = day.quarter();
修改
(生成新对象)
import dayjs from "dayjs";
import utc from "dayjs/plugin/utc";
dayjs.extend(utc);
let day = dayjs();
// 增加
let day1 = day.add(1, "day");
// 减少
let day2 = day.subtract(1, "week");
// 一年的开始
let day3 = day.startOf("year");
// 一月的结束
let day4 = day.endOf("month");
// utc时间
let utc = day.utc();
// 本地时间
let local = utc.local();
输出
import dayjs from "dayjs";
import isLeapYear from "dayjs/plugin/isLeapYear";
dayjs.extend(isLeapYear);
let day = dayjs();
// 格式化字符串
let format = day.format("YYYY-MM-DD HH:mm:ss:SSS");
// 毫秒时间戳
let millisecond = day.valueOf();
// 秒时间戳
let second = day.unix();
// Date对象
let date = day.toDate();
// 是否有效时间
let isValid = day.isValid();
// 当前月份的天数
let daysInMonth = day.daysInMonth();
// 是否闰年(需要导入isLeapYear)
let isLeapYear = day.isLeapYear();