JavaSCript中的Date對象
Date物件
Date物件和String物件不太一樣,定義了一字串,其實就是一個String對象,就可以直接呼叫屬性和方法。
Date物件的使用,必須使用new關鍵字來創(chuàng)建,否則,無法呼叫Date物件的屬性和方法。
?
#建立Date物件的方法
(1)建立目前(現(xiàn)在)日期物件的實例,不帶任何參數(shù)
var today = new Date();
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>php.cn</title> <script> //創(chuàng)建現(xiàn)在的日期時間對象實例 //today就是剛創(chuàng)建的Date對象實例 var today=new Date(); document.write(today); </script> </head> <body> </body> </html>
(2)建立指定時間戳記的日期物件實例,參數(shù)是時間戳記。
時間戳記:是指某一個時間距離1970年1月1日0時0分0秒,過去了多少毫秒值(1秒=1000毫秒)。
var timer = new Date(10000); ?//時間是1970年1月1日0時0分10秒
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>php.cn</title> <script> //指定毫秒值 var time=new Date(20000); document.write(time); </script> </head> <body> </body> </html>
#(3)指定一個字串的日期時間訊息,參數(shù)是一個日期時間字串
var timer = new Date(“2016/11/11 10:00:00”);
#範例:計算你今天多大了?
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>php.cn</title> <script> //計算你今年多大了 //1.創(chuàng)建現(xiàn)在的日期對象,取出當前的毫秒值 var now = new Date(); var nowTime = now.getTime(); //2.創(chuàng)建出生日期時的日期對象,取出那時的毫秒值 var ago = new Date("1992/10/10"); var agoTime = ago.getTime(); //3.兩個毫秒相減 var str=(nowTime-agoTime)/1000/3600/24/365; document.write("你今年"+str+"歲了") </script> </head> <body> </body> </html>
(4)指定多個數(shù)值參數(shù)
var timer = new Date(2015+100,4,25,10,20,0); ?//順序為:年、月、日、時、分、秒,年、月、日是必須的。
舉例:計算自己再活多少天,能活到100歲。
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>php.cn</title> <script> //計算你今年多大了 //1.創(chuàng)建現(xiàn)在的日期對象,取出當前的毫秒值 var now = new Date(); var nowTime = now.getTime(); //2.創(chuàng)建未來日期時的日期對象,取出那時的毫秒值 var future = new Date(1992+100,10,10); var futureTime = future.getTime(); //3.兩個毫秒相減 var str=(futureTime-nowTime)/1000/3600/24; document.write("你還要活"+str+"天,才能到100歲"); </script> </head> <body> </body> </html>
getFullYear():取得四位的年份。
getMonth():取得月份,取值0-11。
getDate():取得幾號,取值1-31
getHours():取得小時數(shù)。
?getMinutes():分鐘數(shù)
#getSeconds():秒數(shù)
getMilliseconds( )毫秒
getDay()星期
#getTime()毫秒值,距離1970年1月1日至今的毫秒值