js实现日期转换

字符串转换成日期格式:

'20130505'.replace(/^(\d{4})(\d{2})(\d{2})$/, "$1-$2-$3");   结果:  "2013-05-05"  ;

这个toLocaleString貌似有点问题,现在的时间明明是上午获取到的是下午6点

new Date(+new Date()+8*3600*1000).toLocaleString()

"2020/1/8 下午6:36:08"

toISOString比较靠谱

new Date(+new Date()+8*3600*1000).toISOString()

"2020-01-08T10:36:02.157Z"

方法1:

function formate(){
                var current = new Date(+new Date()+8*3600*1000).toISOString();
                var day = current.split("T")[0];
                var time = current.split("T")[1].split(".")[0];
                return day+" "+time;
            }
            console.log(formate());

方法2:别人总结的

Date.prototype.format = function (format) {
               var args = {
                   "M+": this.getMonth() + 1,
                   "d+": this.getDate(),
                   "h+": this.getHours(),
                   "m+": this.getMinutes(),
                   "s+": this.getSeconds(),
                   "q+": Math.floor((this.getMonth() + 3) / 3),  //quarter
                   "S": this.getMilliseconds()
               };
               if (/(y+)/.test(format))
                   format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
               for (var i in args) {
                   var n = args[i];
                   if (new RegExp("(" + i + ")").test(format))
                       format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? n : ("00" + n).substr(("" + n).length));
               }
               return format;
           };
            alert(new Date().format("yyyy-MM-dd hh:mm:ss"));

方法3:

function getNowFormatDate() {
                var date = new Date();
                var seperator1 = "-";
                var seperator2 = ":";
                var month = date.getMonth() + 1;
                var strDate = date.getDate();
                if (month >= 1 && month <= 9) {
                    month = "0" + month;
                }
                if (strDate >= 0 && strDate <= 9) {
                    strDate = "0" + strDate;
                }
                var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
                        + " " + date.getHours() + seperator2 + date.getMinutes()
                        + seperator2 + date.getSeconds();
                return currentdate;
            }
            console.log(getNowFormatDate());

原博地址:https://blog.csdn.net/weixin_30845171/article/details/96541586

猜你喜欢

转载自www.cnblogs.com/changyuqing/p/12165324.html