Date
創(chuàng)建 Date 實(shí)例用來處理日期和時(shí)間持舆。Date 對象基于1970年1月1日(世界標(biāo)準(zhǔn)時(shí)間)起的毫秒數(shù)嘲碱。
var today = new Date();
var today = new Date(1453094034000); // by timestamp(accurate to the millimeter)
var birthday = new Date('December 17, 1995 03:24:00');
var birthday = new Date('1995-12-17 03:24:00');
var birthday = new Date(1995, 11, 17);
var birthday = new Date(1995, 11, 17, 3, 24, 0);
new Date();
new Date(value);
new Date(dateString);
new Date(year, month[, day[, hour[, minutes[, seconds[, milliseconds]]]]]);
- value
代表自1970年1月1日00:00:00 (世界標(biāo)準(zhǔn)時(shí)間) 起經(jīng)過的毫秒數(shù)荸哟。
- dateString
表示日期的字符串值梗脾。該字符串應(yīng)該能被 Date.parse() 方法識別(符合 IETF-compliant RFC 2822 timestamps 或 version of ISO8601)激况。
- year
代表年份的整數(shù)值虐杯。為了避免2000年問題最好指定4位數(shù)的年份; 使用 1998, 而不要用 98.
- month
代表月份的整數(shù)值從0(1月)到11(12月)帅戒。
- day
代表一個(gè)月中的第幾天的整數(shù)值灯帮,從1開始。
- hour
代表一天中的小時(shí)數(shù)的整數(shù)值 (24小時(shí)制)逻住。
- minute
分鐘數(shù)钟哥。
- second
秒數(shù)。
- millisecond
表示時(shí)間的毫秒部分的整數(shù)值鄙信。
記住一種格式:
YYYY-MM-DD HH:mm:ss
var birthday = new Date('1995-12-17 03:24:00');
常用方法
get
Date.prototype.getTime():返回實(shí)例對象距離1970年1月1日00:00:00對應(yīng)的毫秒數(shù)瞪醋,等同于valueOf方法-
Date.prototype.getDate():返回實(shí)例對象對應(yīng)每個(gè)月的幾號(從1開始)-
Date.prototype.getDay():返回星期,星期日為0装诡,星期一為1银受,以此類推-
Date.prototype.getFullYear():返回四位的年份-
Date.prototype.getMonth():返回月份(0表示1月践盼,11表示12月)-
Date.prototype.getHours():返回小時(shí)(0-23)-
Date.prototype.getMilliseconds():返回毫秒(0-999)-
Date.prototype.getMinutes():返回分鐘(0-59)-
Date.prototype.getSeconds():返回秒(0-59)-
Date.prototype.getTimezoneOffset():返回當(dāng)前時(shí)間與UTC的時(shí)區(qū)差異,以分鐘表示宾巍,返回結(jié)果考慮到了夏令時(shí)因素
set
Date.prototype.setDate(date):設(shè)置實(shí)例對象對應(yīng)的每個(gè)月的幾號(1-31)咕幻,返回改變后毫秒時(shí)間戳-
Date.prototype.setFullYear(year [, month, date]):設(shè)置四位年份-
Date.prototype.setHours(hour [, min, sec, ms]):設(shè)置小時(shí)(0-23)-
Date.prototype.setMilliseconds():設(shè)置毫秒(0-999)-
Date.prototype.setMinutes(min [, sec, ms]):設(shè)置分鐘(0-59)-
Date.prototype.setMonth(month [, date]):設(shè)置月份(0-11)-
Date.prototype.setSeconds(sec [, ms]):設(shè)置秒(0-59)-
Date.prototype.setTime(milliseconds):設(shè)置毫秒時(shí)間戳
Date.prototype.toString()
toString方法返回一個(gè)完整的時(shí)間字符串
var today = new Date();
today.toString(); // "Fri Apr 03 2015 11:17:29 GMT+0800 (CST)"
日期運(yùn)算
類型轉(zhuǎn)換時(shí),Date對象的實(shí)例如果轉(zhuǎn)為數(shù)值顶霞,則等于對應(yīng)的毫秒數(shù)肄程;如果轉(zhuǎn)為字符串,則等于對應(yīng)的日期字符串选浑。所以蓝厌,兩個(gè)日期對象進(jìn)行減法運(yùn)算,返回的就是它們間隔的毫秒數(shù)古徒;進(jìn)行加法運(yùn)算拓提,返回的就是連接后的兩個(gè)字符串。
var then = new Date(2013,2,1);
var now = new Date(2013,3,1);
now - then
// 2678400000
now + then
// "Mon Apr 01 2013 00:00:00 GMT+0800 (CST)Fri Mar 01 2013 00:00:00 GMT+0800 (CST)"