[JavaScript] Date日期、時間與排序

JavaScript
Date

Date為JavaScript原生物件,基於世界標準時間(UTC) 1970 年 1 月 1 日開始的毫秒數值來儲存時間


若早於(UTC) 1970 年 1 月 1 日,其值為負的毫秒數。


完整語法可參見MDN


需特別注意:


JavaScript Date 物件只能由以 Date 作為建構子來產生,如果把 Date 作為一般的函數來呼叫(省略掉 new 運算子)將會得到一個字串而非 Date 物件;與其它 JavaScript 物件不同,它並沒有物件實體語法(例如:以中刮號 [ ] 表示陣列的宣告方式)。


取得當前時間的方法

var currTime = new Date().getTime()

會得到一串數字(毫秒)如: 1605799871636


若資料庫內儲存的上傳時間是以這種毫秒型態的話


從資料庫內讀取毫秒值後,若要執行Date操作,注意需要先new一個Date物件,如下中time


var time = new Date(this.note.createdDate);


可使用格式轉換function如下:

function formatDate(date) {
 var d = new Date(date),
  month = "" + (d.getMonth() + 1),
  day = "" + d.getDate(),
  year = d.getFullYear();

 if (month.length < 2) month = "0" + month;
 if (day.length < 2) day = "0" + day;

 return [year, month, day].join("-");
}


基本概念就是透過Date.prototype的方法:getMonth()、getDate()、getFullYear()來重新組合想要的字串。


© 2021 Hamsterism. All rights reserved github