Home  >  Q&A  >  body text

javascript - After converting the string date into a general time format, it is found that numbers less than 10 will not automatically add 0 in front, as follows


Do not use string splicing (less than 10, manually add 0 in front), are there any other methods?

大家讲道理大家讲道理2646 days ago930

reply all(2)I'll reply

  • 習慣沉默

    習慣沉默2017-06-26 10:58:49

    Usually you don’t just write a JS paragraph to judge. If it’s less than 10, add a 0 in front

    reply
    0
  • 扔个三星炸死你

    扔个三星炸死你2017-06-26 10:58:49

    function formatTime(date) {
      var year = date.getFullYear()
      var month = date.getMonth() + 1
      var day = date.getDate()
    
      var hour = date.getHours()
      var minute = date.getMinutes()
      var second = date.getSeconds()
      return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
    }
    function formatNumber(n) {
      n = n.toString()
      return n[1] ? n : '0' + n
    }

    reply
    0
  • Cancelreply