1、问题描述
js接收到后台传过来的Date类型日期在控制台打印如下,对该数据进行处理,将其转换成yyyy-MM-dd hh:mm:ss 的格式
2、解决思路
- 创建新的Date对象
- 把年月日时分秒分别取出来
- 将取出的数据组合拼接成预期格式的日期
3、代码实现
let date = new Date(oldDate); //创建新的Date对象
let year = date.getFullYear(); //把年月日时分秒分别取出来
year = new String(year);
let month = date.getMonth()+1;
if(month < 10) {
month = "0".concat(month);
}
let day = date.getDate();
if(day < 10) {
day = "0".concat(day);
}
let hour = date.getHours();
if(hour < 10) {
hour = "0".concat(hour);
}
let minute = date.getMinutes();
if(minute < 10) {
minute = "0".concat(minute);
}
let second = date.getSeconds();
if(second < 10) {
second = "0".concat(second);
}
let newDate = year.concat("-",month,"-",day," ",hour,":",minute,":",second); //将取出的数据组合拼接成预期格式的日期
oldDate = newDate;
4、存在问题
此方法比较笨拙,如有更简单方式,欢迎在评论区指出,谢谢。