Day.js 基本使用
文章目录
- Day.js 基本使用
- 一、概述
- 1、中文网
- 2、简介
- 二、基本使用
- 1、安装
- 2、基本使用
- 3、获取当前时间
- 4、根据时间字符串创建时间对象
- 5、根据时间戳创建时间对象
- 6、根据 Date 对象创建时间对象
- 7、获取年份
- 8、获取月份
- 9、获取日期
- 10、传入对象
- 11、传入数组
- 12、UTC 时间
- 13、获取当前时间戳
- 14、Dayjs 复制
- 15、dayjs 对象设置年份
- 三、操作
- 1、加上
- 2、减去
- 3、时间的开始
- 4、时间的结束
- 四、总结
一、概述
1、中文网
2、简介
Day.js 是一个极简的 JavaScript 库,可以为现代浏览器解析、验证、操作和显示日期和时间。
二、基本使用
1、安装
pnpm add dayjs
2、基本使用
import dayjs from "dayjs";
console.log("=====>", dayjs().format("YYYY-MM-DD HH:mm:ss"));
// =====> 2023-09-22 14:56:11
3、获取当前时间
import dayjs from "dayjs";
console.log("=====>", dayjs().format("YYYY-MM-DD HH:mm:ss"));
// =====> 2023-09-22 14:56:11
4、根据时间字符串创建时间对象
import dayjs from "dayjs";
console.log("=====>", dayjs("2018-08-08").format("YYYY-MM-DD HH:mm:ss"));
// =====> 2018-08-08 00:00:00
5、根据时间戳创建时间对象
import dayjs from "dayjs";
console.log("=====>", dayjs(1318781876406).format("YYYY-MM-DD HH:mm:ss"));
// =====> 2011-10-17 11:51:16
6、根据 Date 对象创建时间对象
import dayjs from "dayjs";
console.log("=====>", dayjs(new Date()).format("YYYY-MM-DD HH:mm:ss"));
// =====> 2021-09-22 14:56:11
7、获取年份
import dayjs from "dayjs";
console.log("=====>", dayjs().year());
// =====> 2021
8、获取月份
import dayjs from "dayjs";
console.log("=====>", dayjs().month());
// =====> 8
9、获取日期
import dayjs from "dayjs";
console.log("=====>", dayjs().date());
// =====> 22
10、传入对象
import dayjs from "dayjs";
console.log(
"=====>",
dayjs({ year: 2018, month: 8, day: 8 }).format("YYYY-MM-DD HH:mm:ss")
);
// =====> 2018-08-08 00:00:00
11、传入数组
import dayjs from "dayjs";
console.log("=====>", dayjs([2018, 8, 8]).format("YYYY-MM-DD HH:mm:ss"));
// =====> 2018-08-08 00:00:00
12、UTC 时间
import dayjs from "dayjs";
console.log("=====>", dayjs.utc().format("YYYY-MM-DD HH:mm:ss"));
// =====> 2021-09-22 06:56:11
13、获取当前时间戳
import dayjs from "dayjs";
console.log("=====>", dayjs().valueOf());
// =====> 1632290171000
14、Dayjs 复制
import dayjs from "dayjs";
const dayjs1 = dayjs();
const dayjs2 = dayjs1.clone();
console.log("=====>", dayjs1 === dayjs2);
// =====> false 是两个独立的 Day.js 对象
15、dayjs 对象设置年份
import dayjs from "dayjs";
console.log("=====>", dayjs().set("year", 2018).format("YYYY-MM-DD HH:mm:ss"));
// =====> 2018-09-22 14:56:11
三、操作
1、加上
import dayjs from "dayjs";
console.log("=====>", dayjs().add(1, "year").format("YYYY-MM-DD HH:mm:ss"));
// =====> 2022-09-22 14:56:11
2、减去
import dayjs from "dayjs";
console.log(
"=====>",
dayjs().subtract(1, "year").format("YYYY-MM-DD HH:mm:ss")
);
// =====> 2020-09-22 14:56:11
3、时间的开始
import dayjs from "dayjs";
console.log("=====>", dayjs().startOf("year").format("YYYY-MM-DD HH:mm:ss"));
// =====> 2021-01-01 00:00:00
4、时间的结束
import dayjs from "dayjs";
console.log("=====>", dayjs().endOf("year").format("YYYY-MM-DD HH:mm:ss"));
// =====> 2021-12-31 23:59:59
四、总结
dayjs 是一个轻量的处理时间和日期的库,它的 API 设计的非常简单,使用起来也非常方便,如果你的项目中需要处理时间和日期,那么 dayjs 是一个不错的选择。更多的 API 可以参考官方文档:https://dayjs.fenxianglu.cn/