通过moment转化new Date、时间戳、格式化时间
// 安装和引入moment
// npm install moment --save # npm
// yarn add moment # Yarn
// import moment from 'moment'
//获取当前moment时间
let currentMoment = moment();
//new Date转化
let newDate = new Date(); //Fri Mar 25 2022 14:59:13 GMT+0800 (中国标准时间)
newDate = 'Fri Mar 25 2022 14:59:13 GMT+0800 (中国标准时间)';
// 1、new Date转时间戳
let timeTamp = Date.parse(newDate); //1648191553000
// 2、new Date转moment
let momentTime = moment(newDate); //moment对象
// 3、new Date格式化
let formatTime = moment(newDate).format('YYYY-MM-DD HH:mm:ss'); //2022-03-25 14:59:13
//时间戳转化
timeTamp = 1648191553000;
// 1、时间戳转new Date
newDate = moment(timeTamp).toDate(); //Fri Mar 25 2022 14:59:13 GMT+0800 (中国标准时间)
// 2、时间戳转moment
momentTime = moment(timeTamp); //moment对象
// 3、时间戳格式化
formatTime = moment(timeTamp).format('YYYY-MM-DD HH:mm:ss'); //2022-03-25 14:59:13
//格式化时间转换
formatTime = '20220325 14:59:13';
// 1、YYYY-MM-DD戳转new Date()
newDate = moment(formatTime, 'YYYYMMDD HH:mm:ss').toDate(); //Fri Mar 25 2022 14:59:13 GMT+0800 (中国标准时间)
// 2、YYYY-MM-DD转moment
momentTime = moment(formatTime, 'YYYYMMDD HH:mm:ss'); //moment对象
// 2、YYYY-MM-DD转时间戳
timeTamp = moment(formatTime, 'YYYYMMDD HH:mm:ss').valueOf(); //1648191553000
//注意:HH:mm:ss为24小时制 h:mm:ss为12小时制
官网:https://momentjs.cn/
格式化日期
moment().format('MMMM Do YYYY, h:mm:ss a'); // 五月 22日 2025, 3:19:11 下午
moment().format('dddd'); // 星期四
moment().format("MMM Do YY"); // 5月 22日 25
moment().format('YYYY [escaped] YYYY'); // 2025 escaped 2025
moment().format(); // 2025-05-22T15:19:11+08:00
相对时间
moment("20111031", "YYYYMMDD").fromNow(); // 14 年前
moment("20120620", "YYYYMMDD").fromNow(); // 13 年前
moment().startOf('day').fromNow(); // 15 小时前
moment().endOf('day').fromNow(); // 9 小时后
moment().startOf('hour').fromNow(); // 21 分钟前
日历时间
moment().subtract(10, 'days').calendar(); // 2025/05/12
moment().subtract(6, 'days').calendar(); // 上周五15:21
moment().subtract(3, 'days').calendar(); // 本周一15:21
moment().subtract(1, 'days').calendar(); // 昨天15:21
moment().calendar(); // 今天15:21
moment().add(1, 'days').calendar(); // 明天15:21
moment().add(3, 'days').calendar(); // 本周日15:21
moment().add(10, 'days').calendar(); // 2025/06/01
多语言环境支持
moment.locale(); // zh-cn
moment().format('LT'); // 15:21
moment().format('LTS'); // 15:21:43
moment().format('L'); // 2025/05/22
moment().format('l'); // 2025/5/22
moment().format('LL'); // 2025年5月22日
moment().format('ll'); // 2025年5月22日
moment().format('LLL'); // 2025年5月22日下午3点21分
moment().format('lll'); // 2025年5月22日 15:21
moment().format('LLLL'); // 2025年5月22日星期四下午3点21分
moment().format('llll'); // 2025年5月22日星期四 15:21
本文来自博客园,作者:苏沐~,转载请注明原文链接:https://www.cnblogs.com/sumu80/p/18880448