創(chuàng)建 Date 實例用來處理日期和時間。Date 對象基于1970年1月1日(世界標準時間)起的毫秒數(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 (世界標準時間) 起經(jīng)過的毫秒數(shù)。
- dateString
表示日期的字符串值。該字符串應該能被 Date.parse() 方法識別(符合 IETF-compliant RFC 2822 timestamps 或 version of ISO8601)。
- year
代表年份的整數(shù)值。為了避免2000年問題最好指定4位數(shù)的年份; 使用 1998, 而不要用 98.
- month
代表月份的整數(shù)值從0(1月)到11(12月)。
- day
代表一個月中的第幾天的整數(shù)值,從1開始。
- hour
代表一天中的小時數(shù)的整數(shù)值 (24小時制)。
- minute
分鐘數(shù)。
- second
秒數(shù)。
- millisecond
表示時間的毫秒部分的整數(shù)值。
記住一種格式:
YYYY-MM-DD HH:mm:ss
var birthday = new Date('1995-12-17 03:24:00');
常用方法
get
Date.prototype.getTime():返回實例對象距離1970年1月1日00:00:00對應的毫秒數(shù),等同于valueOf方法-
Date.prototype.getDate():返回實例對象對應每個月的幾號(從1開始)-
Date.prototype.getDay():返回星期,星期日為0,星期一為1,以此類推-
Date.prototype.getFullYear():返回四位的年份-
Date.prototype.getMonth():返回月份(0表示1月,11表示12月)-
Date.prototype.getHours():返回小時(0-23)-
Date.prototype.getMilliseconds():返回毫秒(0-999)-
Date.prototype.getMinutes():返回分鐘(0-59)-
Date.prototype.getSeconds():返回秒(0-59)-
Date.prototype.getTimezoneOffset():返回當前時間與UTC的時區(qū)差異,以分鐘表示,返回結果考慮到了夏令時因素
set
Date.prototype.setDate(date):設置實例對象對應的每個月的幾號(1-31),返回改變后毫秒時間戳-
Date.prototype.setFullYear(year [, month, date]):設置四位年份-
Date.prototype.setHours(hour [, min, sec, ms]):設置小時(0-23)-
Date.prototype.setMilliseconds():設置毫秒(0-999)-
Date.prototype.setMinutes(min [, sec, ms]):設置分鐘(0-59)-
Date.prototype.setMonth(month [, date]):設置月份(0-11)-
Date.prototype.setSeconds(sec [, ms]):設置秒(0-59)-
Date.prototype.setTime(milliseconds):設置毫秒時間戳
Date.prototype.toString()
toString方法返回一個完整的時間字符串
var today = new Date();
today.toString(); // "Fri Apr 03 2015 11:17:29 GMT+0800 (CST)"
日期運算
類型轉換時,Date對象的實例如果轉為數(shù)值,則等于對應的毫秒數(shù);如果轉為字符串,則等于對應的日期字符串。所以,兩個日期對象進行減法運算,返回的就是它們間隔的毫秒數(shù);進行加法運算,返回的就是連接后的兩個字符串。
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)"