如何更改日期格式并在前面添加0

时间:2016-02-09 13:43:51

标签: javascript jquery date

我有这段代码:

CODE JS:

using namespace

输入值为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

如何在前面添加0?如果它是必要的。

提前致谢!

4 个答案:

答案 0 :(得分:1)

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

merge into table1 t
using (select a.table1id, b.branch
         from table1 a                              
           inner join table2 b                        
            on a.table1id = b.table2id                    
         where (b.asd = '1' or b.asd = '3')  
           and b.branch <> a.branch 
       ) as M
 on t.table1id = m.table1id
when matched
  then update set t.branch = m.branch

答案 1 :(得分:0)

使用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 :(得分:0)

您可以尝试:(点击运行代码段以在控制台中查看结果)

&#13;
&#13;
  
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) ; 
&#13;
&#13;
&#13;

答案 3 :(得分:0)

您可以使用正则表达式:

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];
<pre></pre>