getMinutes() 0-9 - How to display two digit numbers?

后端 未结 21 1545
南笙
南笙 2020-12-01 00:42
var date = \"2012-01-18T16:03\";
var date = new Date(date);

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

This returns 3.

21条回答
  •  余生分开走
    2020-12-01 00:55

    Yikes these answers aren't great, even the top post upticked. Here y'go, cross-browser and cleaner int/string conversion. Plus my advice is don't use a variable name 'date' with code like date = Date(...) where you're relying heavily on language case sensitivity (it works, but risky when you're working with server/browser code in different languages with different rules). So assuming the javascript Date in a var current_date:

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

    The technique is take the rightmost 2 characters (slice(-2)) of "0" prepended onto the string value of getMinutes(). So:

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

    and

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

提交回复
热议问题