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

后端 未结 21 1390
南笙
南笙 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:50
    $(".min").append( (date.getMinutes()<10?'0':'') + date.getMinutes() );
    

    new to JS so this was very helpful the most ppl looking at this prob new too so this is how i got it to show in the div called "class="min"

    hope it helps someone

    0 讨论(0)
  • 2020-12-01 00:51
    var d = new Date(date);
    var dd = d.getDate();
    var MM = d.getMonth();
    var mm = d.getMinutes();
    var HH = d.getHours();
    
    // Hour
    var result = ("0" + HH).slice(-2);
    
    // Minutes
    var result = ("0" + mm).slice(-2);
    
    // Month
    var result = ("0" + MM).slice(-2);
    
    0 讨论(0)
  • 2020-12-01 00:52

    you can use moment js :

    moment(date).format('mm')

    example : moment('2019-10-29T21:08').format('mm') ==> 08

    hope it helps someone

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

    I would like to provide a more neat solution to the problem if I may.The accepted answer is very good. But I would have done it like this.

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

    Now if you want to use this.

    console.log(date.getFullMinutes());
    
    0 讨论(0)
  • 2020-12-01 00:54

    I dont see any ES6 answers on here so I will add one using StandardJS formatting

    // ES6 String formatting example
    const time = new Date()
    const tempMinutes = new Date.getMinutes()
    const minutes = (tempMinutes < 10) ? `0${tempMinutes}` : tempMinutes
    
    0 讨论(0)
  • 2020-12-01 00:54

    how about this? it works for me! :)

    var d = new Date();
    var minutes = d.getMinutes().toString().replace(/^(\d)$/, '0$1');
    
    0 讨论(0)
提交回复
热议问题