项目场景:
前端需要处理linux服务器返回的时间,格式如:Mon Apr 25 14:54:44 CST 2022,带CST格式
问题描述
由于linux时间格式CST转成windows时间格式GMT时间存在new Date()导致原时间会加14h,所以在设置时间的时候,需要进行减去14h的操作。
解决方案:
参数date为CST格式时间戳,format为时间格式 yyyy-MM-dd HH:mm:ss
function dateFormat (date, format) {
date = new Date(date)
date.setHours(date.getHours()-14)
const Mo = {
'M+' : date.getMonth() + 1,
'd+' : date.getDate(),
'H+' : date.getHours(),
'm+' : date.getMinutes(),
's+' : date.getSeconds(),
'q+' : Math.floor((date.getMonth() + 3) / 3),
'S' : date.getMilliseconds()
}
if (/(y+)/.test(format))
format = format.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
for (let k in Mo)
if (new RegExp('(' + k + ')').test(format))
format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? Mo[k] : ('00' + Mo[k]).substr(('' + Mo[k]).length))
return format
}
// 调用
let test_time = dateFormat("Mon Apr 25 14:54:44 CST 2022",'yyyy-MM-dd HH:mm:ss')
console.log(test_time )