JavaScript Date對象詳解和實例

最新更新時間:2020年05月28日13:59:00

《猛戳-查看我的博客地圖-總有你意想不到的驚喜》

本文內容:Date對象,用於處理日期和時間

創建Date對象

var date = new Date();
var date = new Date(milliseconds);
var date = new Date('Fri Mar 24 2017 16:42:54 GMT+0800 (中國標準時間)');
var date = new Date(year,month,day,hours,minutes,seconds,milliseconds);

Date對象實例的方法

var date = new Date();
console.log(date);//object類型的輸出 > Fri Mar 24 2017 16:42:54 GMT+0800 (中國標準時間)
console.log(date.timeString());//16:46:19 GMT+0800 (中國標準時間)
console.log(date.String());//Fri Mar 24 2017 16:46:19 GMT+0800 (中國標準時間)
console.log(date.toLocaleString());//2017/3/24 下午4:46:19
console.log(date.toLocaleDateString());//2017/3/24
console.log(date.toLocaleTimeString());//下午4:46:19
console.log(date.toTimeString());//16:46:19 GMT+0800 (中國標準時間)
console.log(date.toJSON());//2017-03-24T08:46:19.944Z 注意:比中國當前時間少8個小時
console.log(date.toISOString());//2017-03-24T09:07:43.633Z
console.log(date.toDateString());//Fri Mar 24 2017

console.log(date.getDate());//一個月中的某一天
console.log(date.getDay());//一週中的某一天 0週日 1週一 ... 6週六
console.log(date.getFullYear());//四位數年份
console.log(date.getHours());//小時
console.log(date.getMilliseconds());//毫秒數
console.log(date.getMinutes());//
console.log(date.getMonth());//月份 0-11
console.log(date.Seconds());//

console.log(date.valueOf());//返回1970.1.1至今的毫秒數 > 1490344974156
console.log(date.getTime());//返回1970.1.1至今的毫秒數

常用的格式

  • 格式一:2020-04-14 14:13:04
let date = new Date().toJSON().slice(0, 10) + ' ' + new Date().toTimeString().slice(0, 8);
  • 格式二,時間戳:1590645910584
let date = new Date().getTime();
  • 格式三:2020-04-14
let date = new Date().toJSON().slice(0, 10);
  • 格式四:14:13:04
let date = new Date().toTimeString().slice(0, 8);
  • 格式五:2020/5/28
let date = new Date().toLocaleDateString();
  • 格式六,獲取指定時間區間的時間戳

20200321凌晨到20200324晚上12點

new Date(2020,2,21,0,0,0,0).getTime()
new Date(2020,2,24,23,59,59,0).getTime()

注意:月份從0起算,1月份對應的是0

  • 格式七,獲取星期幾
let date = new Date().getDay();//0 1 2 3 4 5 6
getDay 0 1 2 3 4 5 6
星期幾 週日 週一 週二 週三 週四 週五 週六

參考資料

感謝閱讀,歡迎評論^-^

打賞我吧^-^

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章