Javascript add leading zeroes to date

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

    For you people from the future (ECMAScript 2017 and beyond)

    Solution

    "use strict"
    
    const today = new Date()
    
    const year = today.getFullYear()
    
    const month = `${today.getMonth() + 1}`.padStart(2, "0")
    
    const day = `${today.getDate()}`.padStart(2, "0")
    
    const stringDate = [day, month, year].join("/") // 13/12/2017
    

    Explaination

    the String.prototype.padStart(targetLength[, padString]) adds as many as possible padString in the String.prototype target so that the new length of the target is targetLength.

    Example

    "use strict"
    
    let month = "9"
    
    month = month.padStart(2, "0") // "09"
    
    let byte = "00000100"
    
    byte = byte.padStart(8, "0") // "00000100"
    

提交回复
热议问题