JavaScript Date(日期) 對象
JavaScript Date 對象
Date 對象用于處理日期和時(shí)間。創(chuàng)建 Data 對象語法如下:
var date_obj = new Date( arg )
arg 為 Data 對象構(gòu)造函數(shù)可選參數(shù)。當(dāng)省略此參數(shù)時(shí),Data 對象會(huì)自動(dòng)將當(dāng)前的日期和時(shí)間保存為才初始值。也可以指定 arg 參數(shù)來設(shè)定 Date 對象的日期與時(shí)間值,可以接受的參數(shù)如下:
arg 參數(shù)說明:
參數(shù)格式 ? ? ??參數(shù)說明與例子
milliseconds ? ?數(shù)字格式,表示 1970 年 1月 1 日 0 時(shí) 到該數(shù)字的毫秒數(shù) ??new Date( 1289403980906 ) ? ?
datestring ? ?字符串表示的日期與時(shí)間,省略時(shí)間則默認(rèn)為 0 點(diǎn) ? ? ?new Date( "Mar 04, 2012 22:15:14" ) ? ?
year, month ? ?4位數(shù)字的年份,0-11 分別表示 1-12 月 ? ??new Date( 2012, 3 ) ? ?
year, month, day ? ?day 用 1-31 表示月中的某天 ? ?new Date( 2012, 3, 4 ) ? ?
year, month, day, hours ? ?hours 用 0-23 表示一天中的24小時(shí) ??new Date( 2012, 3, 4, 22 ) ? ?
year, month, day, hours, minutes ? ?minutes 用 0-59 表示分鐘數(shù) ?new Date( 2012, 3, 4, 22, 15 ) ? ?
year, month, day, hours, minutes, seconds ? ?seconds 用 0-59 表示秒數(shù) ? ?new Date( 2012, 3, 4, 22, 15, 14 ) ? ?
year, month, day, hours, minutes, seconds, microseconds ? ?microseconds 用 0-999 表示毫秒數(shù) ? ?new Date( 2012, 3, 4, 22, 15, 14, 100 ) ? ?
創(chuàng)建日期
Date 對象用于處理日期和時(shí)間。?
可以通過 new 關(guān)鍵詞來定義 Date 對象。以下代碼定義了名為 myDate 的 Date 對象:
有四種方式初始化日期:
new Date() // 當(dāng)前日期和時(shí)間
new Date(milliseconds) //返回從 1970 年 1 月 1 日至今的毫秒數(shù)
new Date(dateString)
new Date(year, month, day, hours, minutes, seconds, milliseconds)
上面的參數(shù)大多數(shù)都是可選的,在不指定的情況下,默認(rèn)參數(shù)是0。
<p從 1970="" 年="" 1="" 月="" 日通用一天計(jì)算為86,400,000毫秒
實(shí)例化一個(gè)日期的一些例子:
var today = new Date()
var d1 = new Date("October 13, 1975 11:13:00")
var d2 = new Date(79,5,24)
var d3 = new Date(79,5,24,11,33,0)
設(shè)置日期
通過使用針對日期對象的方法,我們可以很容易地對日期進(jìn)行操作。
在下面的例子中,我們?yōu)槿掌趯ο笤O(shè)置了一個(gè)特定的日期 (2010 年 1 月 14 日):
var myDate=new Date();
myDate.setFullYear(2010,0,14);
在下面的例子中,我們將日期對象設(shè)置為 5 天后的日期:
var myDate=new Date();
myDate.setDate(myDate.getDate()+5);
注意:?如果增加天數(shù)會(huì)改變月份或者年份,那么日期對象會(huì)自動(dòng)完成這種轉(zhuǎn)換。
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文網(wǎng)(php.cn)</title> <script type="text/javascript"> var d = new Date(); document.write("現(xiàn)在是:" + d); </script> </head> <body> </body> </html>
兩個(gè)日期比較
日期對象也可用于比較兩個(gè)日期。
下面的代碼將當(dāng)前日期與 2100 年 1 月 14 日做了比較:
var x=new Date();
x.setFullYear(2100,0,14);
var today = new Date();
if (x>today)
{
alert("今天是2100年1月14日之前");
}
else
{
alert("今天是2100年1月14日之后");
}