js實現日期轉換


根據時間(2020-07-20 10:23:21)轉換成秒,可用於兩個時間的比較

let time = new Date("2020-07-20 10:23:21").getTime();

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

獲取時間毫秒 var time = Date.now();

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

字符串轉換成日期格式:

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

toLocaleString獲取的是本地時間(當前電腦的時間)

new Date(+new Date()).toLocaleString()

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

toISOString獲取的是國際時間,和北京時間8小時時差。

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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM