Show you the code !
封装
dateChange.js
/*
** 时间戳转换成指定格式日期
**
** formats格式包括:
** 1. Y-m-d
** 2. Y-m-d H:i:s
** 3. Y年m月d日
** 4. Y年m月d日 H时i分
**
** eg.
** dateFormat(11111111111111, 'Y年m月d日 H时i分')
** → "2322年02月06日 03时45分"
*/
export function dateFormat (timestamp, formats) {
formats = formats || 'Y-m-d';
var zero = function (value) {
if (value < 10) {
return '0' + value;
}
return value;
};
// 单位为毫秒
var myDate = timestamp? new Date(timestamp): new Date();
// 单位为秒
// const myDate = timestamp? new Date(timestamp * 1000): new Date();
var year = myDate.getFullYear();
var month = zero(myDate.getMonth() + 1);
var day = zero(myDate.getDate());
var hour = zero(myDate.getHours());
var minite = zero(myDate.getMinutes());
var second = zero(myDate.getSeconds());
return formats.replace(/Y|m|d|H|i|s/ig, function (matches) {
return ({
Y: year,
m: month,
d: day,
H: hour,
i: minite,
s: second
})[matches];
});
};
/*
** 日期时间转时间戳
**
** eg.
** dateToStamp(11111111111111, '2021-05-06 19:37:43')
** → "1620301063"
*/
export function dateToStamp (date) {
// getTime() 返回的数值单位是毫秒,转换为秒
return (new Date(date)).getTime() / 1000;
}
使用
代码中已经有了相关举例,使用时 import
一下就好。当然,多处用到,可将相应的代码挂载到Vue的原型上,这里就不举例了