js获取当前时间 及时间戳的转换

     
 
1.获取当前时间:
      结果格式 ://  2020年10月10日12时14分58秒
      function getFromTime(str){
              var dt= new Date(str),                 // 获取时间
                   Y = dt.getFullYear(),            //获取 年 (四位)
                   Mont= dt.getMonth()+1,      //获取 月 (0-11,0代表1月)
                   Day= dt.getDate(),               //获取 日 (1-31)
                   Hous = dt.getHours(),         //获取 小时 (0-23)
                   Min= dt.getMinutes(),          //获取 分(0-59)
                   Sec = dt.getSeconds();       //获取秒 (0-59)
           return  Y+'年'+Mont+'月'+Day+'日'+Hous+'时'+Min+'分'+Sec+'秒';
       }
            
      var  mytime = dt.getTime();    // 获取当前时间毫秒数(从1970.1.1开始的毫秒数)
      var  Day = dt.getDay();           // 获取当前星期X(0-6),0代表周日
      var mytime = dt.getMilliseconds();         //获取当前毫秒数(0-999);
      var mytime = dt.toLocaleDateString(); //获取当前年月日 :2020/10/10
      var mytime = dt.toLocaleTimeString();   //获取当前时间 :下午2:46:06
 
2.用js将从后台得到的时间戳 ( 毫秒数 ) 转换为想要的日期格式:
 
    如果我们想把从后台得到的时间戳(毫秒数)转换成 
               2019年12月27日 14时36分26秒   或者是   2019/12/27  14:36:26
    方法:
           var  mytime = new Date(1602303298972).toLocaleString(); // 结果 : 2020/10/10 下午12:14:58
            
           如果上面不是你想要的结果,封装以下方法你再试试
      1.     Date.prototype.toLocaleString = function(){
             return this.getFullYear()+'年'+(this.getMonth() + 1) + '月' +this.getDate() + '日' + this.getHours() + '点' + this.getMinutes() + '分' + this.getSeconds() + '秒';
             }           
                var  mytime = new Date(1602303298972).toLocaleString(); 
              console.log( mytime )   //  结果: 2020年10月10日12点14分58秒
 
            
       2.   Date.prototype.toLocaleString = function(){
             return this.getFullYear()+'/'+(this.getMonth() + 1) + '/' +this.getDate() + '/' + this.getHours() + ':' + this.getMinutes() + ':' + this.getSeconds() ;
             }           
                var  mytime = new Date(1602303298972).toLocaleString(); 
              console.log( mytime )   //  结果: 2020/10/10/ 12:14:58
 
 
       
原文地址:https://www.cnblogs.com/whx123/p/12108306.html