Day.js教程

dayjs是一个轻量的处理时间和日期的 JavaScript 库,这里是dayjs的github网址https://github.com/iamkun/dayjs

一、dayjs好处

  • 🕒 和Moment.js有着相同的API和模式
  • 💪 不可变、持久性
  • 🔥 提供链式调用
  • 🌐 国际化标准
  • 📦 超小的压缩体积,仅仅有2kb左右
  • 👫 极大多数的浏览器兼容

二、 dayjs安装和引入

  • npm方式
npm install dayjs --save

var dayjs = require('dayjs');
dayjs().format();
  • cnd方式
npm install dayjs --save

var dayjs = require('dayjs');
dayjs().format();

三、API中文文档

https://github.com/iamkun/dayjs/blob/master/docs/zh-cn/API-reference.md

Day.js 的返回值都是新的 Dayjs 对象

四、dayjs 解析相关的API

  • 直接运行 dayjs(),得到包含当前时间和日期的 Dayjs 对象
dayjs()  //返回当前时间 Fri Sep 27 2024 11:22:12 GMT+0800
  • 可以解析传入的一个标准的ISO 8601时间字符串。
dayjs('1995-12-25') //Sun, 24 Dec 1995 16:00:00 GMT
  • 可以解析传入的一个 Javascript Date 对象。
dayjs(new Date(2018, 8, 18)) //Mon, 17 Sep 2018 16:00:00 GMT
  • 可以解析传入的一个 Unix 时间戳 (13 位数字)。
dayjs(1318781876406) //Sun, 16 Oct 2011 16:17:56 GMT
  • Dayjs 对象是不可变的,如果您想获得一个对象的拷贝,请执行 .clone()。 向 dayjs() 里传入一个 Dayjs 对象也能实现同样的效果。
dayjs(Dayjs)
dayjs().clone()
  • 检测当前 Dayjs 对象是否是一个有效的时间
dayjs().isValid()

五、dayjs 获取和设置相关的API

在这里插入图片描述

  • 获取或设置年份。
dayjs().year() //2024
dayjs().year(2000) //Sun, 28 May 2000 06:14:07 GMT
  • 获取或设置月份。从 0 开始
dayjs().month() //8 实际上9月
dayjs().month(0) //Sat Jan 27 2024 11:29:57 GMT+0800 
  • 获取或设置日期。从 1 开始
dayjs().day() //5 当天是星期五
dayjs().day(0) //Sun Sep 22 2024 11:30:21 GMT+0800 被强行设置为上周日
  • 获取或设置小时
dayjs().hour()  //11 24小时制
dayjs().hour(12) //Fri Sep 27 2024 12:31:50
  • 获取或设置分钟。
dayjs().minute() //33 
dayjs().minute(59) // Fri Sep 27 2024 11:59:25 
  • 获取或设置秒
dayjs().second()
dayjs().second(1)
  • 获取或设置毫秒。
dayjs().millisecond()
dayjs().millisecond(1)

六、dayjs 操作相关API

您可以对 Dayjs 对象如下增加减少之类的操作

增加时间并返回一个新的 Dayjs() 对象。

dayjs().add(value : Number, unit : String);
dayjs().add(7, 'day'); //在当前的基础上加7天

减少时间并返回一个新的 Dayjs() 对象。

dayjs().subtract(value : Number, unit : String);
dayjs().subtract(7, 'day'); //在当前基础上减少7天

返回当前时间的开头时间的 Dayjs() 对象,如月份的第一天。

dayjs().startOf(unit : String);
dayjs().startOf('month'); //Tue, 30 Apr 2019 16:00:00 GMT 

返回当前时间的末尾时间的 Dayjs() 对象,如月份的最后一天。

dayjs().endOf(unit : String);
dayjs().endOf('month'); //Fri, 31 May 2019 15:59:59 GMT

七、显示相关的API

格式化 Dayjs 对象并展示。

接收一系列的时间日期字符串并替换成相应的值。

dayjs().format(String)
dayjs('2019-01-25').format('YYYY-MM-DD HH:mm:ss') 
dayjs().format('YYYY-MM-DD') 
dayjs().format('YYYY-MM') //2019

在这里插入图片描述

在这里插入图片描述

  • 获取两个 Dayjs 对象的时间差,默认毫秒。
const date1 = dayjs('2019-01-25')
const date2 = dayjs('2018-06-05')
date1.diff(date2) // 20214000000
date1.diff(date2, 'month') // 7
date1.diff(date2, 'month', true) // 7.645161290322581
date1.diff(date2, 'day') // 233
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值