網站搜尋

javascript - getMinutes() 0-9 - 如何顯示兩位數字?


var date = "2012-01-18T16:03";
var date = new Date(date);

console.log(date.getMinutes());
console.log(date.getMinutes().length)

這返回 3。

  1. 我該如何讓它返回 '03'?
  2. 為什麼 .length 會返回 undefined?

我試了這個,但沒有用:

如果 strlen == 1 那麼 num=('0' + num);

答案#1

var date = new Date("2012-01-18T16:03");

console.log( (date.getMinutes() < 10 ? '0' : '') + date.getMinutes() );

答案#2

這個解決方案是跨瀏覽器的,並且整數/字串轉換更乾淨。我的建議是不使用名為 'date' 的變數,像 date=Date(...) 這樣的代碼,因為你在很大程度上依賴語言的大小寫敏感性(它可以運作,但當你在不同語言、不同規則的伺服器/瀏覽器代碼中工作時風險很大)。所以假設在一個變數 current_date 中有 JavaScript Date:

mins = ('0'+current_date.getMinutes()).slice(-2);

這個技巧是取字串值 getMinutes() 前加上 "0" 的最右邊兩個字元 (slice(-2))。所以:

"0"+"12" -> "012".slice(-2) -> "12"

和

"0"+"1" -> "01".slice(-2) -> "01"

答案#3

另一種簡短的方法是使用以下方式在分鐘前補零:

String(date.getMinutes()).padStart(2, "0");

意思:將字串長度補至兩個字元,如果某個字元缺失,則在此位置設置 0。

請參見文檔:str.padStart(targetLength, padString)

答案#4

優雅的 ES6 函數,用於將日期格式化為 hh:mm:ss:

const leadingZero = (num) => `0${num}`.slice(-2);

const formatTime = (date) =>
  [date.getHours(), date.getMinutes(), date.getSeconds()]
  .map(leadingZero)
  .join(':');

答案#5

使用 ECMAScript 國際化 API,更多資訊:

const date_string = "2012-01-18T16:03";
const date = new Date(date_string);
const twoDigitMinutes = date.toLocaleString("en-us", {year: 'numeric', month: 'numeric', day: 'numeric', hour: '2-digit', minute: '2-digit', second: "2-digit"});

console.log(twoDigitMinutes);

答案#6

如果可以的話,我想提供一個更整潔的解決方案。已接受的答案很好,但我會這樣做。

Date.prototype.getFullMinutes = function () {
   if (this.getMinutes() < 10) {
       return '0' + this.getMinutes();
   }
   return this.getMinutes();
};

現在如果你想使用這個。

console.log(date.getFullMinutes());

答案#7

我建議:

var minutes = data.getMinutes();
minutes = minutes > 9 ? minutes : '0' + minutes;

少了一次函數呼叫。考慮效能總是好的。它也很簡短;