概念
- 北京时间和utc
- utc:世界协调时
- 以英国格林威治时间为标准
- utc时间和北京时间相差8小时
- utc的凌晨相当于北京时间的上午8点
- 时间戳timestamp
- 某个utc时间到utc 1970 -1-1凌晨经过的毫秒数(可以是秒数,可以用小数部分记录)
- 注意点:时间戳表示的是utc时间的差异
- 对于服务器的影响
- 服务器可能会部署到世界的任何位置
- 服务器内部应该统一使用utc时间或时间戳,包括数据库
- 对于客户端的影响
- 客户端要给不同地区的客户友好的显示时间
- 客户端应该把时间戳或utc时间转换为本地时间显示
简介
最好使用时间戳
- 安装
npm install moment --save # npm
yarn add moment # Yarn
spm install moment --save # spm
meteor add momentjs:moment # meteor
bower install moment --save # bower (deprecated)
- 格式化时间(使用日期令牌转换)
moment().format('MMMM Do YYYY, h:mm:ss a'); // 三月 18日 2025, 7:34:48 晚上
moment().format('dddd'); // 星期二
moment().format("MMM Do YY"); // 3月 18日 25
moment().format('YYYY [escaped] YYYY'); // 2025 escaped 2025
moment().format();
- 得到指定格式的时间
const formats = ["YYYY-MM-DD HH:mm:ss","YYYY-M-D H:m:s","x"];
moment("1970-02-05 00:00:00",formats,true).toString();
true表示是否严格检查
判断是否符合.isValid()
- 得到当前时间
moment().toString()
// 获得时间戳:+moment()或moment().valueOf()
moment().utc().toString()
// 获得时间戳:+moment.utc()或moment.utc().valueOf()
- 显示(客户端)
const m = moment.utc("2025-1-1 23:44:11",formats,true);
console.log(m.format("YYYY年MM月DD日 HH时mm分上述、秒"));
console.log(m.local().format("YYYY年MM月DD日 HH时mm分上述、秒"));
- 距当前时间
const m = moment.utc("2025-1-1 23:44:11",formats,true);
console.log(m.local().fromNom());