本文實例講述了JS實現獲取毫秒值及轉換成年月日時分秒的方法。分享給大家供大家參考,具體如下:
時間日期對象
創建方式一
var date=new Date();
創建方式二 兼容性最強 推薦使用
var date1=new Date("2017/08-26 15:15:15");
創建方式三
var date2=new Date(2017,9,18,23,15,23);
返回結果是從1970/01/01到現在的毫秒值
var date = Date.now();var date = +new Date();var date = new Date().getTime();var date = new Date().valueOf();
把日期解析成毫秒值
var date=Date.parse("2017-05-24 18:23:14");
傳入毫秒值 獲取該毫秒值對應的時間日期
var date =new Date(Date.now());
getDate()
獲取日 1-31getDay ()
獲取星期 0-6(0代表周日)getMonth ()
獲取月 0-11(1月從0開始)getFullYear ()
獲取完整年份(瀏覽器都支持)getHours ()
獲取小時 0-23getMinutes ()
獲取分鐘 0-59getSeconds ()
獲取秒 0-59getMilliseconds ()
獲取毫秒 (1s = 1000ms)getTime ()
返回累計毫秒數(從1970/1/1午夜)
自己簡單封裝的輸入毫秒值,根據不同的參數獲取年月日時分秒
獲取你想要的時間格式 參數(毫秒值,int) int取值為:0:年1:月2:日3:時4:分5:秒
如:
console.log(getTime(1523604904000,1));function getTime(second,getDateType) { var date =new Date(second); if(getDateType==0){ return date.getFullYear(); }else if(getDateType==1){ if((date.getMonth()+1)<=9){ return "0"+(date.getMonth()+1); }else { return date.getMonth()+1; } }else if(getDateType==2){ if(date.getDate()<=9){ return "0"+date.getDate(); }else { return date.getDate(); } }else if(getDateType==3){ if(date.getHours()<=9){ return "0"+date.getHours(); }else { return date.getHours(); } }else if(getDateType==4){ if(date.getMinutes()<=9){ return "0"+date.getMinutes(); }else { return date.getMinutes(); } }else if(getDateType==5){ return date.getSeconds (); }else { alert("輸入時間格式有誤!"); return; }}
這里使用在線HTML/CSS/JavaScript代碼運行工具:http://tools.VeVB.COm/code/HtmlJsRun,測試結果如下:
PS:這里再為大家推薦幾款比較實用的天數計算在線工具供大家使用:
在線日期/天數計算器:
http://tools.VeVB.COm/jisuanqi/date_jisuanqi
在線日期計算器/相差天數計算器:
http://tools.VeVB.COm/jisuanqi/datecalc
在線日期天數差計算器:
http://tools.VeVB.COm/jisuanqi/onlinedatejsq
在線天數計算器:
http://tools.VeVB.COm/jisuanqi/datejsq
更多關于JavaScript相關內容感興趣的讀者可查看本站專題:《JavaScript時間與日期操作技巧總結》、《JavaScript+HTML5特效與技巧匯總》、《JavaScript錯誤與調試技巧總結》、《JavaScript數據結構與算法技巧總結》及《JavaScript數學運算用法總結》
希望本文所述對大家JavaScript程序設計有所幫助。
新聞熱點
疑難解答