Javascript date - Leading 0 for days and months where applicable

前端 未结 9 2023
情话喂你
情话喂你 2020-12-15 05:07

Is there a clean way of adding a 0 in front of the day or month when the day or month is less than 10:

var myDate = new Date();
var prettyDate =(myDate.getFu         


        
9条回答
  •  时光说笑
    2020-12-15 05:56

    The easiest way to do this is to prepend a zero and then use .slice(-2). With this function you always return the last 2 characters of a string.

    var month = 8;

    var monthWithLeadingZeros = ('0' + month).slice(-2);

    Checkout this example: http://codepen.io/Shven/pen/vLgQMQ?editors=101

提交回复
热议问题