Javascript add leading zeroes to date

后端 未结 25 1813
执笔经年
执笔经年 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:34

    The new modern way to do this is to use toLocaleDateString, because it allows you not only to format a date with proper localization, but even to pass format options to archive the desired result:

    var date = new Date(2018, 2, 1);
    var result = date.toLocaleDateString("en-GB", { // you can skip the first argument
      year: "numeric",
      month: "2-digit",
      day: "2-digit",
    });
    console.log(result); // outputs “01/03/2018”

    When you skip the first argument it will detect the browser language, instead. Alternatively, you can use 2-digit on the year option, too.

    If you don't need to support old browsers like IE10, this is the cleanest way to do the job. IE10 and lower versions won't understand the options argument.

    Please note, there is also toLocaleTimeString, that allows you to localize and format the time of a date.

提交回复
热议问题