js时间——转换为我们需要的格式

首先认识时间:

var time1 = "2020-08-08T08:08:08.888";       //第一种:北京时间,位于东8区,比格林威治时间早8个小时
var time2 = "2020-08-08T08:08:08.888+0000";       //第二种:格林威治时间
如何将这两种转为我们常用的:2020-08-08 08:08:08

第一种:提取出对应的年月日,时分秒,然后拼凑成我们需要的格式

function getTimeFun1(str) {
            if (str) {
                let reg = new RegExp("[+0000]$");
                if (str.match(reg)) {
                    t = new Date(+(new Date(str)) - 8 * 3600 * 1000);
                } else {
                    t = new Date(str);
                }
            } else {
                t = new Date();
            }
            let year = t.getFullYear(), //获取年
                month = t.getMonth() + 1,    //
                day = t.getDate(),     //
                hour = t.getHours(),    //小时
                min = t.getMinutes(),  //分钟
                sec = t.getSeconds();  //
            month = month < 10 ? "0" + month : month;   //格式化月
            day = day < 10 ? "0" + day : day;
            hour = hour < 10 ? "0" + hour : hour;
            min = min < 10 ? "0" + min : min;
            sec = sec < 10 ? "0" + sec : sec;

            return {
                year, mon, day, hour, min, sec
            };
        }
//调用方法
let timeObj = getTimeFun1(time1);
//①返回值timeObj是一个对象,包括年月日时分秒,根据情况自己提取拼凑;
//②time1是日期参数,数据类型为字符串;
//③如果不传参,返回当前时间

第二种:通过转换成时间戳再转换成时间

function getTimeFun2(str) {
            if (str) {
                let reg = new RegExp("[+0000]$");
                if (str.match(reg)) {
                    t = new Date(str);
                } else {
                    t = new Date(+new Date(str) + 8 * 3600 * 1000);
                }
            } else {
                t = new Date(+new Date() + 8 * 3600 * 1000);
            }
            let date = t.toISOString().replace(/T/g, ' ').replace(/.[d]{3}Z/, '')
            return date;
        }
//调用方法
let date = getTimeFun2(time2);
//①返回值2020-08-08 08:08:08
//②time2是日期参数,数据类型为字符串;
//③如果不传参,返回当前时间
原文地址:https://www.cnblogs.com/xihailong/p/13426395.html