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

后端 未结 21 1388
南笙
南笙 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 01:01

    I suggest:

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

    it is one function call fewer. It is always good to think about performance. It is short as well;

    0 讨论(0)
  • 2020-12-01 01:01

    For two digit minutes use: new Date().toLocaleFormat("%M")

    0 讨论(0)
  • 2020-12-01 01:04

    I assume you would need the value as string. You could use the code below. It will always return give you the two digit minutes as string.

    var date = new Date(date);
    var min = date.getMinutes();
    
    if (min < 10) {
    min = '0' + min;
    } else {
    min = min + '';
    }
    console.log(min);
    

    Hope this helps.

    0 讨论(0)
  • 2020-12-01 01:10

    I usually use this piece of code :

    var start = new Date(timestamp),
        startMinutes = start.getMinutes() < 10 ? '0' + start.getMinutes() : start.getMinutes();
    

    It is quite similar to the @ogur accepted answer but does not concatenate an empty string in the case that 0 is not needed. Not sure it is better. Just an other way to do it !

    0 讨论(0)
  • 2020-12-01 01:11

    Another short way is to fill the minutes with a leading zero using:

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

    Meaning: Make the string two chars long, if a char is missing then set 0 at this position.

    See docs at str.padStart(targetLength, padString)

    0 讨论(0)
  • 2020-12-01 01:11

    you should check if it is less than 10... not looking for the length of it , because this is a number and not a string

    0 讨论(0)
提交回复
热议问题