JavaScript-Date對(duì)象

兩個(gè)基礎(chǔ)知識(shí):

  1. JavaScript內(nèi)的時(shí)間戳指的是當(dāng)前時(shí)間到1970年1月1日00:00:00 UTC對(duì)應(yīng)的毫秒數(shù);
  2. 標(biāo)準(zhǔn)時(shí)間:
  • GMT:格林威治標(biāo)準(zhǔn)時(shí)間,指位于英國倫敦郊區(qū)的皇家格林威治天文臺(tái)的標(biāo)準(zhǔn)時(shí)間,由于地球的自轉(zhuǎn)不規(guī)則,因此導(dǎo)致GMT時(shí)間有誤差;
  • UTC:世界標(biāo)準(zhǔn)時(shí)間,

Date對(duì)象是JavaScript提供的日期和時(shí)間的操作接口。它可以表示的時(shí)間范圍是,1970年1月1日00:00:00前后的各1億天(單位為毫秒)。

Date()對(duì)象可以作為普通函數(shù)直接調(diào)用,無論有沒有參數(shù),總是返回當(dāng)前時(shí)間。

new Date()構(gòu)造函數(shù)

日期對(duì)象的創(chuàng)建,使用new操作符和Date構(gòu)造函數(shù):

  var now = new Date();

作為構(gòu)造函數(shù),如果不加參數(shù),會(huì)返回代表當(dāng)前時(shí)間的對(duì)象:

var now = new Date();
console.log(now);

// 2017-08-25T02:39:35.181Z

作為構(gòu)造函數(shù),Date()對(duì)象可以接收多種格式參數(shù):

  1. new Date(milliseconds)

Date對(duì)象接受從1970年1月1日00:00:00 UTC開始計(jì)算的毫秒數(shù)作為參數(shù)。這意味著如果將Unix時(shí)間戳(單位為秒)作為參數(shù),必須將Unix時(shí)間戳乘以1000。

Date構(gòu)造函數(shù)的參數(shù)可以是一個(gè)負(fù)數(shù),表示1970年1月1日之前的時(shí)間。

new Date(1378218728000)
// Tue Sep 03 2013 22:32:08 GMT+0800 (CST)

// 1970年1月2日的零時(shí)
var Jan02_1970 = new Date(3600 * 24 * 1000);
// Fri Jan 02 1970 08:00:00 GMT+0800 (CST)

// 1969年12月31日的零時(shí)
var Dec31_1969 = new Date(-3600 * 24 * 1000);
// Wed Dec 31 1969 08:00:00 GMT+0800 (CST)
  1. new Date(datestring)

Date對(duì)象還接受一個(gè)日期字符串作為參數(shù),返回所對(duì)應(yīng)的時(shí)間。所有可以被Date.parse()方法解析的日期字符串,都可以當(dāng)作Date對(duì)象的參數(shù)。

new Date('January 6, 2013');

<!-- Date 2013-01-05T16:00:00.000Z -->

日期字符串的完整格式是“month day, year hours:minutes:seconds”,比如“December 25, 1995 13:30:00”。如果省略了小時(shí)、分鐘或秒數(shù),這些值會(huì)被設(shè)為0。

  1. new Date(year, month [, day, hours, minutes, seconds, ms])

在多個(gè)參數(shù)的情況下,Date對(duì)象將其分別視作對(duì)應(yīng)的年、月、日、小時(shí)、分鐘、秒和毫秒。如果采用這種用法,最少需要指定兩個(gè)參數(shù)(年和月),其他參數(shù)都是可選的,默認(rèn)等于0。如果只使用年一個(gè)參數(shù),Date對(duì)象會(huì)將其解釋為毫秒數(shù)。

各個(gè)參數(shù)的取值范圍為:

  • year:四位年份,如果寫成兩位數(shù),則加上1900
  • month:表示月份,0表示一月,11表示12月
  • date:表示日期,1到31
  • hour:表示小時(shí),0到23
  • minute:表示分鐘,0到59
  • second:表示秒鐘,0到59
  • ms:表示毫秒,0到999

上面的參數(shù)如果超出了范圍,那么將進(jìn)行自動(dòng)折算,比如月份為15,將折算為下一年的4月。

上面的參數(shù)如果為負(fù)數(shù),表示從基準(zhǔn)扣除的時(shí)間。

年份如果是0到99,會(huì)自動(dòng)加上1900。比如,0表示1900年,1表示1901年;如果為負(fù)數(shù),則表示公元前。

日期的運(yùn)算

類型轉(zhuǎn)換時(shí),Date對(duì)象的實(shí)例如果轉(zhuǎn)為數(shù)值,則等于對(duì)應(yīng)的毫秒數(shù);如果轉(zhuǎn)為字符串,則等于對(duì)應(yīng)的日期字符串。所以,兩個(gè)日期對(duì)象進(jìn)行減法運(yùn)算,返回的就是它們間隔的毫秒數(shù);進(jìn)行加法運(yùn)算,返回的就是連接后的兩個(gè)字符串。

var then = new Date(1993, 11, 02);
var now = new Date(2017, 8, 27);

console.log(now - then);
// 751680000000

console.log(now + then);
// Wed Sep 27 2017 00:00:00 GMT+0800 (CST)Thu Dec 02 1993 00:00:00 GMT+0800 (CST)?

Date對(duì)象的靜態(tài)方法

Date.now()

now方法返回當(dāng)前距離1970年1月1日00:00:00的毫秒數(shù)(Unix時(shí)間戳乘以1000)。。

console.log(Date.now());

Date.parse()

parse方法用來解析日期字符串,返回距離1970年1月1日 00:00:00的毫秒數(shù)

日期字符串的格式應(yīng)該完全或者部分符合YYYY-MM-DDTHH:mm:ss.sssZ格式,Z表示時(shí)區(qū),是可選的

如果傳入Date.parse()方法的字符串不能表示日期,返回NaN

默認(rèn)情況下,Date對(duì)象返回的都是當(dāng)前時(shí)區(qū)的時(shí)間。

Date.UTC()

返回UTC時(shí)間。該方法接受年、月、日等變量作為參數(shù),返回當(dāng)前距離1970年1月1日 00:00:00 UTC的毫秒數(shù)。

Date實(shí)例對(duì)象的方法

Date實(shí)例對(duì)象一般分為3類:

  1. to類:從Date對(duì)象返回一個(gè)字符串,表示指定的時(shí)間。
  2. get類:獲取Date對(duì)象的日期和時(shí)間。
  3. set類:設(shè)置Date對(duì)象的日期和時(shí)間。

to類方法

Date.prototype.toString()

返回一個(gè)完整的日期字符串。

var now = new Date(2017, 8, 27);
console.log(now);
// 2017-09-26T16:00:00.000Z

console.log(now.toString());
// Wed Sep 27 2017 00:00:00 GMT+0800 (CST)

Date.prototype.toUTCString()

返回對(duì)應(yīng)的UTC時(shí)間,也就是時(shí)區(qū)時(shí)間。

var now = new Date(2017, 8, 27);
console.log(now);
// 2017-09-26T16:00:00.000Z

console.log(now.toUTCString());
// Tue, 26 Sep 2017 16:00:00 GMT

Date.prototype.toISOString()

返回對(duì)應(yīng)時(shí)間的ISO8601寫法。返回的也是UTC時(shí)區(qū)時(shí)間。

var now = new Date(2017, 8, 27);
console.log(now);
// 2017-09-26T16:00:00.000Z

console.log(now.toISOString());
// 2017-09-26T16:00:00.000Z

Date.prototype.toJSON()

返回一個(gè)符合JSON格式的ISO格式的日期字符串,與toISOString方法的返回結(jié)果完全相同。

Date.prototype.toDateString()

返回日期字符串。

var now = new Date(2017, 8, 27);
console.log(now);
// 2017-09-26T16:00:00.000Z

console.log(now.toDateString());
// Wed Sep 27 2017

Date.prototype.toTimeString()

返回時(shí)間字符串。

var now = new Date(2017, 8, 27);
console.log(now);
// 2017-09-26T16:00:00.000Z

console.log(now.toTimeString());
// 00:00:00 GMT+0800 (CST)

Date.prototype.toLocaleDateString()

返回當(dāng)?shù)厝掌谧址?/p>

var now = new Date(2017, 8, 27);
console.log(now);
// 2017-09-26T16:00:00.000Z

console.log(now.toLocaleDateString());
// 2017-9-27

get類方法

  • getTime():返回距離1970年1月1日00:00:00的毫秒數(shù),等同于valueOf方法。
  • getDate():返回實(shí)例對(duì)象對(duì)應(yīng)每個(gè)月的幾號(hào)(從1開始)。
  • getDay():返回星期幾,星期日為0,星期一為1,以此類推。
  • getYear():返回距離1900的年數(shù)。
  • getFullYear():返回四位的年份。
  • getMonth():返回月份(0表示1月,11表示12月)。
  • getHours():返回小時(shí)(0-23)。
  • getMilliseconds():返回毫秒(0-999)。
  • getMinutes():返回分鐘(0-59)。
  • getSeconds():返回秒(0-59)。
  • getTimezoneOffset():返回當(dāng)前時(shí)間與UTC的時(shí)區(qū)差異,以分鐘表示,返回結(jié)果考慮到了夏令時(shí)因素。

set類方法

  • setDate(date):設(shè)置實(shí)例對(duì)象對(duì)應(yīng)的每個(gè)月的幾號(hào)(1-31),返回改變后毫秒時(shí)間戳。
  • setYear(year): 設(shè)置距離1900年的年數(shù)。
  • setFullYear(year [, month, date]):設(shè)置四位年份。
  • setHours(hour [, min, sec, ms]):設(shè)置小時(shí)(0-23)。
  • setMilliseconds():設(shè)置毫秒(0-999)。
  • setMinutes(min [, sec, ms]):設(shè)置分鐘(0-59)。
  • setMonth(month [, date]):設(shè)置月份(0-11)。
  • setSeconds(sec [, ms]):設(shè)置秒(0-59)。
  • setTime(milliseconds):設(shè)置毫秒時(shí)間戳。

參考信息:《JavaScript 標(biāo)準(zhǔn)參考教程(alpha)》,by 阮一峰

小練習(xí):

  1. 寫一個(gè)函數(shù)getChIntv,獲取從當(dāng)前時(shí)間到指定日期的間隔時(shí)間
function getChIntv(datestr) {
  var targetDate = new Date(datestr);
  var curDate = new Date();
  var offset = Math.abs(targetDate - curDate);
  var totalSeconds = Math.floor(offset / 1000);
  var second = totalSeconds % 60;
  var totalMinutes = Math.floor(totalSeconds / 60);
  var minute = totalMinutes % 60;
  var totalHours = Math.floor(totalMinutes / 60);
  var hours = totalHours % 24;
  var days = Math.floor(totalHours / 24);

  return targetDate.toLocaleDateString() + ' 距離現(xiàn)在:' + days + '天' + hours + '小時(shí)' + minute + '分鐘' + second + '秒';
}

var offectTime = getChIntv('2017, 7, 27');
console.log(offectTime);
// 2017-7-27 距離現(xiàn)在:31天13小時(shí)2分鐘3秒

  1. 把hh-mm-dd格式數(shù)字日期改成中文日期
function getChsDate(inputDate) {
  var dict = ["零", "一", "二", "三", "四", "五", "六", "七", "八", "九", "十", "十一", "十二", "十三", "十四", "十五", "十六", "十七",
    "十八", "十九", "二十", "二十一", "二十二", "二十三", "二十四", "二十五", "二十六", "二十七", "二十八", "二十九", "三十",
    "三十一"
  ];
  var arr = inputDate.split('-'); //  從'-'處把字符串分割成字符串?dāng)?shù)組
  // [ '2017', '08', '27' ]

  var arrYear = arr[0].split(''); //  將年份分割成數(shù)組
  // [ '2', '0', '1', '7' ]

  var strYear = '';
  for (var i = 0; i < 4; i++) {
    strYear += dict[parseInt(arrYear[i])];
  }
  var strMonth = dict[parseInt(arr[1])];
  var strDate = dict[parseInt(arr[2])];
  return strYear + '年' + strMonth + '月' + strDate + '日';
}
var result = getChsDate('2017-08-27');
console.log(result);
  1. 寫一個(gè)函數(shù),參數(shù)為時(shí)間對(duì)象毫秒數(shù)的字符串格式,返回值為字符串。假設(shè)參數(shù)為時(shí)間對(duì)象毫秒數(shù)t,根據(jù)t的時(shí)間分別返回如下字符串:
  • 剛剛( t 距當(dāng)前時(shí)間不到1分鐘時(shí)間間隔)
  • 3分鐘前 (t距當(dāng)前時(shí)間大于等于1分鐘,小于1小時(shí))
  • 8小時(shí)前 (t 距離當(dāng)前時(shí)間大于等于1小時(shí),小于24小時(shí))
  • 3天前 (t 距離當(dāng)前時(shí)間大于等于24小時(shí),小于30天)
  • 2個(gè)月前 (t 距離當(dāng)前時(shí)間大于等于30天小于12個(gè)月)
  • 8年前 (t 距離當(dāng)前時(shí)間大于等于12個(gè)月)
function pastTime(inputTime) {
  var curTime = new Date();
  var nowTime = curTime.getTime();
  var offsetMinute = Math.floor((nowTime - inputTime) / 1000 / 60);

  var offsetTime;
  if (offsetMinute < 1) {
    offsetTime = '剛剛';
  } else if (offsetMinute < 60) {
    offsetTime = offsetMinute + '分鐘前';
  } else if (offsetMinute < 1440) {
    offsetTime = Math.floor(offsetMinute / 60) + '小時(shí)前';
  } else if (offsetMinute < 43200) {
    offsetTime = Math.floor(offsetMinute / 60 / 24) + '天前';
  } else if (offsetMinute < 518400) {
    offsetTime = Math.floor(offsetMinute / 60 / 24 / 30) + '個(gè)月前';
  } else {
    offsetTime = Math.floor(offsetMinute / 60 / 24 / 30 / 12) + '年前';
  }
  return offsetTime;
}

var str = pastTime('1483200000000');
console.log(str);
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容