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