-1

I should format my datetime value in javascript to this format yyyy-MM-dd hh:mm:ss

I tried this

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

But it result to this

2017-8-31 02:00:00

  1. month and date should be 2-digit (08 intead of 8)

What could be the best workaround?

*type on minutes is edited

rickyProgrammer
  • 1,177
  • 4
  • 27
  • 63

2 Answers2

1

Nothing wrong with your code. Javascript returns the integer < 10 in single digit only. Format it to string of 2 with a function.

    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);
Amit Kumar Singh
  • 4,393
  • 2
  • 9
  • 22
0

You forgot () for getMinutes(), to have 2 digits :

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();
Philippe
  • 960
  • 2
  • 12
  • 29