Javascript用前导零切片日期/时间

时间:2018-05-29 18:15:42

标签: javascript slice

我试图在日期的某个部分之前添加前导0。例如,如果它是上午9:00,我想显示09:00而不是9:0。我希望能够添加一个前导零,所以我可以将其插入到MySQL编码中。

我得到的结果是

2018-05-029 019:07:016

这是我的Javascript代码:



 var login_date="";
                                                
    var d = new Date();
                                                
    var year            = d.getFullYear();
    var month           = d.getMonth()+1; /*months are from 0 - 11 */
    month               = '0' + month.toString().slice(-2);
    var day             = d.getDate();
    day                 = '0' + day.toString().slice(-2);
    var hour            = d.getHours();
    hour                = '0' + hour.toString().slice(-2);
    var minute          = d.getMinutes();
    minute              = '0' + minute.toString().slice(-2);
    var second          = d.getSeconds();
    second              = '0' + second.toString().slice(-2);
                                                         
    login_date = year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second;
    console.log(login_date);




3 个答案:

答案 0 :(得分:1)

您可以检查字符的变量length,如果小于2,则添加0.

这样的事情:

var d = new Date();

var day = d.getDate();
var month = d.getMonth() + 1;
var year = d.getFullYear();
var hour =  d.getHours();
var minute =  d.getMinutes();
var second =  d.getSeconds();


if (month.toString().length < 2) month = '0' + month;
if (hour.toString().length < 2) hour = '0' + hour;
if (minute.toString().length < 2) minute = '0' + minute;
if (second.toString().length < 2) second = '0' + second;

console.log(year + '-' + month + '-' + day + " " + hour + ":" + minute + ":" + second)

答案 1 :(得分:0)

您可以创建一个函数addZero(),在必要时处理0的连接。这是代码:

&#13;
&#13;
let addZero = (el) => ((el.toString().length == 1) ? '0' : '') + el.toString();

var login_date = "";

var d = new Date();

var year = d.getFullYear();
var month = d.getMonth() + 1; /*months are from 0 - 11 */
var day = d.getDate();
var hour = d.getHours();
var minute = d.getMinutes();
var second = d.getSeconds();


login_date = year + "-" + addZero(month) + "-" + addZero(day) + " " + addZero(hour) + ":" + addZero(minute) + ":" + addZero(second);

document.write(login_date);
&#13;
&#13;
&#13;

答案 2 :(得分:0)

您可以检查该值是否小于10,以便在开头添加“0”。

例如

var login_date = year + "-" 
                + (month < 10 ? "0" + month : month) + "-" 
                + (day < 10 ? "0" + day : day) + " " 
                + (hour < 10 ? "0" + hour : hour) + ":" 
                + (minute < 10 ? "0" + minute : minute) + ":" 
                + (second < 10 ? "0" + second : second) ;

您的最终字符串可以定义为:

{{1}}