JavaScript 时间格式化
/**
* @param {date} 标准时间格式:Fri Nov 17 2017 09:26:23 GMT+0800 (标准时间)
* @param {type} 类型
* type == 1 ---> "yyyy-mm-dd hh:MM:ss.fff"
* type == 2 ---> "yyyymmddhhMMss"
* type == '' ---> "yyyy-mm-dd hh:MM:ss"
* zone ---> 时区,与世界标准时间的时差,
*/
export const formatDate = (datef, type, zone = 0) => {
let date = datef
if (zone) {
const localTime = date.getTime();
const localOffset = date.getTimezoneOffset()*60000; //获得当地时间偏移的毫秒数
const utc = localTime + localOffset; //utc即GMT时间
const hawaii = utc + (3600000*zone) + 60 * 60 * 1000;
date = new Date(hawaii);
}
var year = date.getFullYear(); //年
var month =
date.getMonth() + 1 < 10
? "0" + (date.getMonth() + 1)
: date.getMonth() + 1; //月
var day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate(); //日
var hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours(); //时
var minutes =
date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes(); //分
var seconds =
date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds(); //秒
var milliseconds =
date.getMilliseconds() < 10
? "0" + date.getMilliseconds()
: date.getMilliseconds(); //毫秒
if (type == 1) {
return (
year +
"-" +
month +
"-" +
day +
" " +
hour +
":" +
minutes +
":" +
seconds +
"." +
milliseconds
);
} else if (type == 2) {
return (
year + "" + month + "" + day + "" + hour + "" + minutes + "" + seconds
);
} else if (type == 3) {
return year + "-" + month + "-" + day;
} else {
return (
year +
"-" +
month +
"-" +
day +
" " +
hour +
":" +
minutes +
":" +
seconds
);
}
}