时间转换插件--moment & dayjs

236 阅读2分钟

moment插件

背景:根据格式获取想要的格式,如年-月-日 时:分:秒、年-月-日 时、时

可安装moment插件

yarn add moment
格式化日期
moment().format('YYYY-MM-DD, HH:mm:ss'); 	//2024-04-28 02:50:47
moment().format('MMMM Do YYYY, h:mm:ss a'); // 四月 28日 2024, 2:49:09 下午
moment().format('dddd');                    // 星期日
moment().format("MMM Do YY");               // 4月 28日 24
moment().format('YYYY [escaped] YYYY');     // 2024 escaped 2024
moment().format();                          // 2024-04-28T14:49:09+08:00
相对时间
moment('2024-04-28 13:03:21').format('HH:mm:ss') //'13:03:21' 24小时制
moment('2024-04-28 13:03:21').format('hh:mm:ss') //'01:03:21'	12小时制
moment("20111031", "YYYYMMDD").fromNow(); // 12 年前
moment("20120620", "YYYYMMDD").fromNow(); // 12 年前
moment().startOf('day').fromNow();        // 15 小时前
moment().endOf('day').fromNow();          // 9 小时后
moment().startOf('hour').fromNow();       // 1 小时前
日历时间
moment().subtract(10, 'days').calendar(); // 2024/04/18
moment().subtract(6, 'days').calendar();  // 本周一14:49
moment().subtract(3, 'days').calendar();  // 本周四14:49
moment().subtract(1, 'days').calendar();  // 昨天14:49
moment().calendar();                      // 今天14:49
moment().add(1, 'days').calendar();       // 明天14:49
moment().add(3, 'days').calendar();       // 下周三14:49
moment().add(10, 'days').calendar();      // 2024/05/08

解析格式:

输入示例描述
YY18两位数的年份
YYYY2018四位数的年份
M1-12月份,从 1 开始
MM01-12月份,两位数
MMMJan-Dec缩写的月份名称
MMMMJanuary-December完整的月份名称
D1-31月份里的一天
DD01-31月份里的一天,两位数
H0-23小时
HH00-23小时,两位数
h1-12小时, 12 小时制
hh01-12小时, 12 小时制, 两位数
m0-59分钟
mm00-59分钟,两位数
s0-59
ss00-59秒,两位数
S0-9毫秒,一位数
SS00-99毫秒,两位数
SSS000-999毫秒,三位数

dayjs插件

yarn add dayjs

直接调用 dayjs() 将返回一个包含当前日期和时间的 Day.js 对象。

dayjs()						//M {$L: 'en', $d: Sun Apr 28 2024 14:53:02 GMT+0800 (中国标准时间), $y: 2024, $M: 3, $D: 28, …}
new Date()				//Sun Apr 28 2024 14:53:09 GMT+0800 (中国标准时间)
dayjs(new Date())	//M {$L: 'en', $d: Sun Apr 28 2024 14:53:14 GMT+0800 (中国标准时间), $y: 2024, $M: 3, $D: 28, …}
dayjs().millisecond()
dayjs().second() // => new Date().getSeconds()
dayjs().minute()
dayjs().hour()
dayjs().day()
dayjs().year()
dayjs().month()
...
dayjs().get('year')
dayjs().get('month') // start 0
dayjs().get('date')
dayjs().get('hour')
dayjs().get('minute')
dayjs().get('second')
dayjs().get('millisecond')