其实已经有好用的时间格式化工具了,http://momentjs.cn/
写这个时间格式化函数主要是满足一个需求:将uct时间转化为本地时间且格式化时间;
function formatTime(time) {
return time < 10 ? "0" + time : time;
};
// 参数 时间字符串, 格式化的样式
function localTime(time, formatString="yyyy-MM-dd hh:mm:ss"){
let date = new Date(time);
// 将utc时区时间转为当前本地时间
let currentTimeZoneOffsetInHours = date.getTimezoneOffset()/60;
date.setHours(date.getHours()-currentTimeZoneOffsetInHours)
formatString = formatString.replace("yyyy",date.getFullYear())
.replace("MM", date.getMonth() + 1)
.replace("dd", formatTime(date.getDate()))
.replace("hh", formatTime(date.getHours()))
.replace("mm", formatTime(date.getMinutes()))
.replace("ss", formatTime(date.getSeconds()));
return formatString;
};
export default {
localTime: localTime
};
更新一下:
因为我们的项目涉及到了多个时间组件,比如有日期+时间的组件,单纯的时间组件,要求需要存零时区的时间,数据到前端的时候显示当地时间。项目里新引入了moment.js
于是更新了一下这个文件如下,让它用起来更方便。
import moment from 'moment'
function localDate(date) {
// 将utc时区时间转为当前本地时间,返回moment对象,然后使用format方法格式化时间
if(moment(date).isValid()){
return moment.utc(date).local();
}
return ;
}
function utcDate(date, componentType){
// 将本地时间转为utc时间,按规定的格式化
switch(componentType){
case "DateInput":
return moment(date).utc().millisecond(0).format().replace("Z","");
case "PureTime":
return moment(date).utc().millisecond(0).format("HH:mm:ss.SSS")
case "PureDate":
return moment(date).utc().millisecond(0).format("YYYY-MM-DD")
}
return ;
}
export default {
localDate,
utcDate
};