【问题标题】:How to change date format and add a 0 in front [duplicate]如何更改日期格式并在前面添加 0 [重复]
【发布时间】:2016-05-19 12:47:03
【问题描述】:

我有这个代码:

代码 JS:

var completeD = start.format("YYYY/MM/DD HH:mm");
var dt = new Date(completeD);
console.log(dt)   //here it's display Tue Feb 09 2016 02:00:00 GMT+0200 (EET)  
console.log(dt.getHours() + ":" + dt.getMinutes()); //the input value is 2:0

输入值为2:0,应为02:00

如何在前面添加一个 0 ...?如果需要的话。

提前致谢!

【问题讨论】:

  • 你为什么不格式化为var completeD = start.format("HH:mm");去想想呢?

标签: javascript jquery date


【解决方案1】:

使用pad 函数

function pad(var value) {
    if(value < 10) {
        return '0' + value;
    } else {
        return value;
    }
}

现在可以使用了

 console.log( pad( dt.getHours() ) + ":" + pad ( dt.getMinutes()) ); // outputs 02:00

【讨论】:

    【解决方案2】:

    简单的方法是写一个函数来纠正字符串:

    function normalize(n) {
        if (n < 10) {
            n = "0" + n;
        }
        return n;
    } 
    var completeD = start.format("YYYY/MM/DD HH:mm");
    var dt = new Date(completeD);
    console.log(normalize(dt.getHours()) + ":" + normalize(dt.getMinutes()));
    

    【讨论】:

      【解决方案3】:

      你可以试试这个:(点击运行代码sn-p在控制台查看结果)

        
      var dt = new Date();
      console.log(dt)   //here it's display Tue Feb 09 2016 02:00:00 GMT+0200 (EET) 
      var hours = dt.getHours();
      var minute = dt.getMinutes();
        
      if(hours.toString().length == 1 ) hours = "0"+hours;
      if(minute.toString().length == 1 ) minute = "0"+minute;
      console.log(hours + ":" + minute); //the input value is 2:0
      alert(hours + ":" + minute) ; 

      【讨论】:

        【解决方案4】:

        你可以使用正则表达式:

        var dt = 'Tue Feb 09 2016 02:00:00 GMT+0530 (India Standard Time)';//new Date();
        document.querySelector('pre').innerHTML = dt.match(/(\d\d:\d\d)/g)[0];
        &lt;pre&gt;&lt;/pre&gt;

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-08-18
          • 2011-12-23
          • 2016-10-09
          • 1970-01-01
          • 1970-01-01
          • 2023-03-27
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多