有时候后端返回的时间格式是这样的:2021-5-31T08:56:24Z
但是我们需要的可能是:2021-5-31 08:56:24 或是这样:Tue Jun 01 2021 10:53:34 GMT+0800 (中国标准时间)
正常我们可以使用字符串截取方法等操作也可以实现
但是为了不改代码的情况下都能获取到我们想要的
function toTime(strTime) {
if (!strTime) {
return '';
}
var myDate = new Date(strTime + '+0800');
if (myDate == 'Invalid Date') {
strTime = strTime.replace(/T/g, ' ');
strTime = strTime.replace(/-/g, '/');
strTime = strTime.replace(/\.\d+/, ' ');
myDate = new Date(strTime + '+0800');
}
return myDate;
}
console.log(toTime(new Date())) //Tue Jun 01 2021 10:53:34 GMT+0800 (中国标准时间)
console.log(toTime('2021-5-31T08:56:24Z')) //Mon May 31 2021 08:56:24 GMT+0800 (中国标准时间)
无论传入怎样的格式都可以得到我们想要的