Javascript add leading zeroes to date

后端 未结 25 1835
执笔经年
执笔经年 2020-11-22 02:50

I\'ve created this script to calculate the date for 10 days in advance in the format of dd/mm/yyyy:

var MyDate = new Date();
var MyDateString = new Date();
M         


        
25条回答
  •  孤街浪徒
    2020-11-22 03:44

    Another option, using a built-in function to do the padding (but resulting in quite long code!):

    myDateString = myDate.getDate().toLocaleString('en-US', {minimumIntegerDigits: 2})
      + '/' + (myDate.getMonth()+1).toLocaleString('en-US', {minimumIntegerDigits: 2})
      + '/' + myDate.getFullYear();
    
    // '12/06/2017'
    

    And another, manipulating strings with regular expressions:

    var myDateString = myDate.toISOString().replace(/T.*/, '').replace(/-/g, '/');
    
    // '2017/06/12'
    

    But be aware that one will show the year at the start and the day at the end.

提交回复
热议问题