时间处理工具momentjs
为什么要用?
自己写的时间处理工具类有兼容性, 网上找都处理很多可靠的很少,几个项目被坑惨了
以前用的
formatDate(timestamp, fmt = 'yyyy-MM-dd hh:mm:ss') {
if (!timestamp) return null;
let date = null;
if (timestamp instanceof Date) {
date = timestamp;
} else {
// 兼容
date = new Date(timestamp.replace(new RegExp(/-/gm), '/'));
}
const o = {
'y+': date.getFullYear(),
'M+': date.getMonth() + 1,
'd+': date.getDate(),
'h+': date.getHours(),
'm+': date.getMinutes(),
's+': date.getSeconds(),
'w+': date.getDay(),
};
Object.entries(o).forEach(([rxp, value]) => {
fmt = fmt.replace(new RegExp(rxp), ($1) => {
const str = `0000${value}`;
if ($1 === 'M' || $1 === 'd') {
if (value > 9) {
return value;
}
} else if ($1 === 'ww') {
const week = '一二三四五六日'.substr(value - 1, 1);
return `周${week}`;
}
return str.substr(str.length - $1.length);
});
});
return fmt;
},
有时候还要经常处理获取月份啊周啊什么的bug 实在多,自己写实在麻烦还考虑不全,还有兼容性,崩溃...下面用moment来处理时间常用方式
format
moment().format(); // "2014-09-08T08:02:17-05:00" (ISO 8601,无小数秒钟)
moment().format("dddd, MMMM Do YYYY, h:mm:ss a"); // "Sunday, February 14th 2010, 3:25:50 pm"
moment().format("ddd, hA"); // "Sun, 3PM"
moment('gibberish').format('YYYY-MM-DD'); // "Invalid date"
格式
说明 | 令牌 | 输出| |
---|---|---|
月份 | M | 1 2 ... 11 12 |
Mo | 1st 2nd ... 11th 12th | |
MM 01 02 ... 11 12 | ||
MMM Jan Feb ... Nov Dec | ||
MMMM January February ... November December | ||
季度 | Q | 1 2 3 4 |
Qo | 1st 2nd 3rd 4th | |
月份的日期 | D | 1 2 ... 30 31 |
Do | 1st 2nd ... 30th 31st | |
DD | 01 02 ... 30 31 | |
年份的日期 | DDD | 1 2 ... 364 365 |
DDDo | 1st 2nd ... 364th 365th | |
DDDD | 001 002 ... 364 365 | |
星期几 | d | 0 1 ... 5 6 |
do | 0th 1st ... 5th 6th | |
dd | Su Mo ... Fr Sa | |
ddd | Sun Mon ... Fri Sat | |
dddd | Sunday Monday ... Friday Saturday | |
星期几(语言环境) | e | 0 1 ... 5 6 |
星期几(ISO) | E | 1 2 ... 6 7 |
年份的星期 | w | 1 2 ... 52 53 |
wo | ||
ww | 01 02 ... 52 53 | |
年份的星期(ISO) | W | 1 2 ... 52 53 |
Wo | 1st 2nd ... 52nd 53rd | |
WW | 01 02 ... 52 53 | |
Unix | 时间戳 X 1360013296 | |
Unix | 毫秒时间戳 x 1360013296123 |
还有挺多具体请参考中文文档
来源:oschina
链接:https://my.oschina.net/u/3552880/blog/3217908