标准的new Date()的格式为:new Date(year, month, day, hours, minutes, seconds, milliseconds),new Date(yyyy-mm-dd hh:mm:ss)等格式存在兼容问题。
export function stringToDate(str) {
// 字符串必需符合以下规则:
// 按照年月日时分秒顺序;
// 至少需指定到日,日与时之间需要加空格;
// 连接符只能是一个字符,只有日的或者最后一个的连接符可以省略。
// 例如如:2018-01-2 00:0:3,2018年2月20日 12时30,2018-2-1。
const reg = /^(\d{1,4})\D(0[^0]|1[012]|[^0])\D(0[^0]|[12]\d|3[01]|[^0])(?:[^\d\s])?(?:\s|$)(?:([01]\d|2[0-3]|[^0])|$)(?:\D|$)(?:([0-5]\d|[^0])|$)(?:\D|$)(?:([0-5]\d|[^0])|$)(?:\D|$)(?:(\d{1,3})|$)\D?$/;
if (!reg.test(str)) {
throw new Error('字符串格式错误');
}
let year = 0, month = 0, day = 0, hours = 0, minutes = 0, seconds = 0, milliseconds = 0;
str.replace(reg, (...arg) => {
year = Number(arg[1]);
month = Number(arg[2]) - 1;
day = Number(arg[3]);
if (arg[4]) {
hours = Number(arg[4]);
}
if (arg[5]) {
minutes = Number(arg[5]);
}
if (arg[6]) {
seconds = Number(arg[6]);
}
if (arg[7]) {
milliseconds = Number(arg[7]);
}
});
return new Date(year, month, day, hours, minutes, seconds, milliseconds);
}
// 将utc时间格式化
export function formatUtcTime(v) {
if (!v) {
return ''
}
let date = new Date(v);
return date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
}
//将时间戳格式化
export function formatDate(datetime) {
var date = new Date(datetime * 1000);
var year = date.getFullYear(),
month = ("0" + (date.getMonth() + 1)).slice(-2),
sdate = ("0" + date.getDate()).slice(-2),
hour = ("0" + date.getHours()).slice(-2),
minute = ("0" + date.getMinutes()).slice(-2),
second = ("0" + date.getSeconds()).slice(-2);
return year + "-" + month + "-" + sdate + " " + hour + ":" + minute + ":" + second;
}
safafi浏览器只能显示:yyyy/mm/dd hh:mm:ss格式或yyyy-MM-ddTHH:mm:ss的时间
// 将utc时间格式化(适应safari)
export function utc2beijing(v) {
if (!v) {
return ''
}
let date = formatUtcTime(v); // 将utc时间格式化为 yyyy-mm-dd hh:mm:ss
date = stringToDate(date); // new Date(yyyy-mm-dd hh:mm:ss)存在不兼容,new Date(y,m,d,h,m,s)
date = new Date(date);
return date.getFullYear() + "/" + ((date.getMonth() + 1) < 10 ? '0' + (date.getMonth() + 1) : (date.getMonth() + 1)) + "/" + (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
}