獲取時間:var myDate = new Date();//獲取系統當前時間
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( ); //獲取日期與時間
var time = new Date();
time.getTimezoneOffset(); // -480,返回本地時間與UTC時間相差的分鐘數
獲取當前時間戳:
第一種方法:
var timestamp =Date.parse(new Date());
得到的結果:1280977330000 注意:這里得到的結果將后三位(毫秒)轉換成了000顯示,使用時可能會出現問題。例如動態添加頁面元素id的時候,不建議使用。
第二種方法:
var timestamp =(new Date()).valueOf();
結果:1280977330748
第三種方法:
var timestamp=new Date().getTime();
結果:1280977330748
注意事項:
js中單獨調用new Date(),例如:document.write(new Date());這個方法會把時間直接寫在頁面上,顯示的結果是:Mar 31 10:10:43 UTC+0800 2012 這種格式的時間.
但是用new Date() 參與計算會自動轉換為從1970.1.1開始的毫秒數。
實例: 中考1.0---現場管理----檢出----打印時間的方法
printingDl.getDate=function(){
var myDate = new Date();
//獲取當前年
var year=myDate.getFullYear();
//獲取當前月
var month=myDate.getMonth()+1;
//獲取當前日
var date=myDate.getDate();
var h=myDate.getHours(); //獲取當前小時數(0-23)
var m=myDate.getMinutes(); //獲取當前分鐘數(0-59)
var s=myDate.getSeconds(); //獲取秒數
var now=year+"年"+month+"月"+date+"日"+h+"時"+m+"分"+s+"秒";
return "打印日期:"+now;
}