1、js中實現時間date對象
var myDate = new Date();//獲取系統當前時間,結果:Wed Aug 09 2017 00:00:00 GMT+0800 (中國標准時間)
2、獲取new Date對象的具體時間戳
var date_in = date1.getTime();//date_in結果:1501862400000
3、獲取特定格式的時間
myDate.getYear(); //獲取當前年份(2位) myDate.getFullYear(); //獲取完整的年份(4位,1970-????) myDate.getMonth(); //獲取當前月份(0-11,0代表1月) myDate.getDate(); //獲取當前日(1-31) myDate.getDay(); //獲取當前星期X(0-6,0代表星期天) myDate.getTime(); //獲取當前時間(從1970.1.1開始的毫秒數) myDate.getHours(); //獲取當前小時數(0-23) myDate.getMinutes(); //獲取當前分鍾數(0-59) myDate.getSeconds(); //獲取當前秒數(0-59) myDate.getMilliseconds(); //獲取當前毫秒數(0-999) myDate.toLocaleDateString(); //獲取當前日期 var mytime=myDate.toLocaleTimeString(); //獲取當前時間 myDate.toLocaleString( ); //獲取日期與時間
4、獲取date1==2017-08-31和date2==2017-09-01
var date1 = new Date().getFullYear() + "-" + (new Date().getMonth() + 1) + "-" + new Date().getDate();
var date3 = Date.parse(new Date(Date.parse((new Date().getFullYear() + "/" + (new Date().getMonth() + 1) + "/" + new Date().getDate()))))+86400000 var date2 = new Date(date3).getFullYear() + "-" + (new Date(date3).getMonth() + 1) + "-" + new Date(date3).getDate(),
5、new Date(參數);
參數格式剖析:
1)new Date(13位JS時間戳) ; 如new Date(1280977330000),結果是:Wed Aug 09 2017 00:00:00 GMT+0800 (中國標准時間)
2)new Date(Date.parse("Y/m/d")) ;如new Date(Date.parse("2017/08/09")),結果是:Wed Aug 09 2017 00:00:00 GMT+0800 (中國標准時間)
將自定義字符串形式的日期轉換成日期對象、並參與計算
var strTime="2011-04-16"; //字符串日期格式
var date= new Date(Date.parse(strTime.replace(/-/g, "/"))); //轉換成Data();
這里的date可以直接參與計算,自動轉換成13位時間戳
6、==========================================================================
js獲取當前時間戳的方法-JavaScript 獲取當前毫秒時間戳有以下三種方法:
var timestamp =Date.parse(new Date()); 結果:1280977330000 //不推薦; 毫秒改成了000顯示
var timestamp =(new Date()).valueOf(); 結果:1280977330748 //推薦;
var timestamp=new Date().getTime(); 結果:1280977330748 //推薦;
js中單獨調用new Date(); 顯示這種格式 Mar 31 10:10:43 UTC+0800 2012
但是用new Date() 參與計算會自動轉換為從1970.1.1開始的毫秒數
-------------------------------------------------------------------------------------------------------------
將自定義字符串形式的日期轉換成日期對象、並參與計算
var strTime="2011-04-16"; //字符串日期格式
var date= new Date(Date.parse(strTime.replace(/-/g, "/"))); //轉換成Data();
這里的date可以直接參與計算,自動轉換成13位時間戳
==========================================================================
上面的new Date()和下面的date.getTime() 在進行計算的時候是相等的;因為new Date()計算時自動轉換成13位長度的毫秒數,如:
將字符串形式的日期轉換成日期對象 var strTime="2011-04-16"; //字符串日期格式 var date1= new Date(Date.parse(strTime.replace(/-/g, "/"))); //轉換成Data(); if (date1 < Date.parse(new Date()) - 86400000) {//這里的date1格式:Wed Aug 09 2017 00:00:00 GMT+0800 (中國標准時間),但是在參與計算的時候,直接轉換成13位的時間戳數據 alert('住房時間不能小於當前時間!'); }