2020-03-18T18:55:27.207转2020-03-18 18:55
安卓会把这个带T字母的时间看做UTC时间格式,(包括ios打包后也会相差8个小时)与北京时间相差8个小时。你要将UTC时间转化为北京时间然后进行格式化。GMT +0800 已经是加了8个小时的了。或者你直接把T替换掉,然后格式化,忘记是看的是哪位大哥的了
// 字符串转换成时间 ios中要把毫秒去掉
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; //输出的也是带T时间格式,但在安卓和ios上时间保持一致
}
最终的代码:
getParseTime:function(time, cFormat){ //('2020-03-18T18:55:27.207', '{y}-{m}-{d} | {h}:{i}' )
if (!time) {
return '';
}
var myDate = new Date(time + '+0800');
if (myDate == 'Invalid Date') {
time = time.replace(/T/g, ' ');
time = time.replace(/-/g, '/');
time = time.replace(/\.\d+/, ' ');//去掉毫秒
myDate = new Date(time + '+0800');
}
time = myDate;
if (time == null) {
return '';
}
if (arguments.length === 0) {
return null
}
var format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
var date
if (typeof time === 'object') {
date = time
} else {
if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
time = parseInt(time)
}
if ((typeof time === 'number') && (time.toString().length === 10)) {
time = time * 1000
}
date = new Date(time)
}
var formatObj = {
y: date.getFullYear(),
m: date.getMonth() + 1,
d: date.getDate(),
h: date.getHours(),
i: date.getMinutes(),
s: date.getSeconds(),
a: date.getDay()
}
var time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
var value = formatObj[key]
// Note: getDay() returns 0 on Sunday
if (key === 'a') {
return ['日', '一', '二', '三', '四', '五', '六'][value]
}
//return value.toString().padStart(2, '0') //时间补零,padStart可能出现兼容问题
return value.toString()
})
return time_str
},
如果时间相差8个小时的就用以下代码:
getParseTime:function(time){
var date = time//"2019-11-23T00:00:00.000+0000";
var arr=date.split("T");
var d=arr[0];
var darr = d.split('-');
var t=arr[1];
var tarr = t.split('.000');
var marr = tarr[0].split(':');
var dd = parseInt(darr[0])+"/"+parseInt(darr[1])+"/"+parseInt(darr[2])+" "+parseInt(marr[0])+":"+parseInt(marr[1])+":"+parseInt(marr[2]);
function formatDateTime (date) {
let time = new Date(Date.parse(date));
time.setTime(time.setHours(time.getHours() + 8));
// alert(time);
// if (!isNaN(time)) {
// return new Date(Date.parse(date.replace(/-/g, "/")));
// } else {
let Y = time.getFullYear() + '-';
let M = addZero(time.getMonth() + 1) + '-';
let D = addZero(time.getDate()) + ' ';
let h = addZero(time.getHours()) + ':';
let m = addZero(time.getMinutes()) + ':';
let s = addZero(time.getSeconds());
return Y + M + D + h + m + s;
// }
};
// 数字补0操作
function addZero(num) {
return num < 10 ? '0' + num : num;
};
return formatDateTime(dd)
// const date = new Date("2019-11-23T00:00:00.000+0000");
// console.log("date:",date);
console.log("Date:",new Date());
},