时间处理
new Date()
let now = new Date()
console.log(now) // Wed Nov 10 2021 10:33:10 GMT+0800 (中国标准时间)
console.log(typeof new Date()) // 'ojbject'
console.dir(new Date())
函数Date的原型上绑定了许多处理时间的函数
示例如下:
now.getFullYear(); //完整的年(4位数,如2021)
now.getMonth(); //当前的月份(0-11,0代表1月) 月份表示需要+1
now.getDate(); //当前的日(今天是多少号,如今天2021/11/10,则此值为10)
now.getDay(); //当前的星期X(0-6,0代表星期天)
now.getHours(); //当前的小时数(0-23)
now.getMinutes(); //当前的分钟数(0-59)
now.getSeconds(); //当前的秒数(0-59)
now.getMilliseconds(); //当前的毫秒数(0-999)
now.toLocaleDateString(); //当前的日期'2021/11/10'
now.toLocaleString(); // 2021/11/10 上午10:40:00'
now.getTime(); //当前的时间戳(从1970.1.1开始的毫秒数)
moment
中文文档:moment
Moment.js 会为 Date
对象创建封装器,而不是修改Date的原型prototype。
const t = moment(new Date())
console.log(t);
console.log(moment());
使用moment获取当前时间与原生Date对比如下:
通过format传入的格式显示不同的时间格式
console.log(moment().format());// 2021-11-10T11:31:03+08:00
console.log(moment().format('YYYY-MM-DD'));//2021-11-10
console.log(moment().format('X')); // 1636515382
console.log(moment().format('x')); // 1636515382805
其他时间示例
-
获取当月开始和结束时间,以时间戳方式显示
let startTime = moment().startOf('month').format('x');
let endTime = moment().endOf('month').format('x'); -
获取当前时间的上/下一个月时间,然后转化为时间戳,把时间戳字符串类型转数值型,才能使用new Date()转化为中国标准时间的Date类型
new Date(Number(moment('1640769104474').subtract(1, 'month').format('x')))
new Date(Number(moment('1640769104474').add(1, 'month').format('x')))
//.add(1, 'month') //(增加数值,增加的类型)
//.subtract(1, 'month') //(减少数值,减少的类型)
提示
moment.js官方总结了两大问题:
- 可变对象
- 包体积过大 在2020年9月,moment.js官方宣布停止开发,进入维护状态,后续不会再为其增加新功能,并建议新项目不要使用moment.js
无缝代替moment.js的dayjs:
- 和moment.js相同的API
- 不可变
- 体积小2kb
逐渐流行的date-fns:
- 模块化、按需引入
- 不可变
- 同时支持 Flow 和 TypeScript
我们可以基于date-fns封装符合UI规范的utils