在Javascript中格式化日期时间

时间:2017-09-13 07:52:01

标签: javascript asp.net-mvc

我应该将javascript中的日期时间值格式化为此格式yyyy-MM-dd hh:mm:ss

我试过这个

  var btf = new Date(value.createDate);
  var billingTimeFormatted = btf.getFullYear() + "-" +  btf.getMonth()  + "-" + btf.getDate() + " " + btf.getHours() + ":" + btf.getMinutes() + ":" + btf.getSeconds();

但结果是

2017-8-31 02:00:00

  1. 月份和日期应为2位数(08 intead of 8)
  2. 什么是最好的解决方法?

    编辑分钟上的*类型

2 个答案:

答案 0 :(得分:1)

您的代码没有错。 Javascript返回整数<仅限10位数。使用函数将其格式化为2的字符串。

    function formatWithZero(val)
    {

     // as per comment by @RobG below, return ('0'+val).slice(-2) will also 
     // do the same thing in lesser lines of code. It works and can be used.
      var value = val.toString();
      if(value.length > 1)
                   return value;

        var str = "00"+value;
        return str.slice(str.length-2,str.length); ;
    }

//I am using Date.now(), you can use your value.
    var btf = new Date(Date.now());

      var billingTimeFormatted = btf.getFullYear() + "-" +  formatWithZero(btf.getMonth())  + "-" + formatWithZero(btf.getDate()) + " " + formatWithZero(btf.getHours()) + ":" + formatWithZero(btf.getMinutes()) + ":" + formatWithZero(btf.getSeconds());
        alert(billingTimeFormatted);

答案 1 :(得分:0)

您忘了() getMinutes(),有两位数:

var btf = new Date();    
var currentMonth = btf.getMonth();
if (currentMonth < 10) { currentMonth = '0' + currentMonth; }
var billingTimeFormatted = btf.getFullYear() + "-" +  currentMonth  + "-" + btf.getDate() + " " + btf.getHours() + ":" + btf.getMinutes() + ":" + btf.getSeconds();