Javascript add leading zeroes to date

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

    You could use ternary operator to format the date like an "if" statement.

    For example:

    var MyDate = new Date();
    MyDate.setDate(MyDate.getDate()+10);
    var MyDateString = (MyDate.getDate() < 10 ? '0' + MyDate.getDate() : MyDate.getDate()) + '/' + ((d.getMonth()+1) < 10 ? '0' + (d.getMonth()+1) : (d.getMonth()+1)) + '/' + MyDate.getFullYear();
    

    So

    (MyDate.getDate() < 10 ? '0' + MyDate.getDate() : MyDate.getDate())
    

    would be similar to an if statement, where if the getDate() returns a value less than 10, then return a '0' + the Date, or else return the date if greater than 10 (since we do not need to add the leading 0). Same for the month.

    Edit: Forgot that getMonth starts with 0, so added the +1 to account for it. Of course you could also just say d.getMonth() < 9 :, but I figured using the +1 would help make it easier to understand.

    0 讨论(0)
  • 2020-11-22 03:24
    function formatDate(jsDate){
      // add leading zeroes to jsDate when days or months are < 10.. 
      // i.e.
      //     formatDate(new Date("1/3/2013")); 
      // returns
      //    "01/03/2103"
      ////////////////////
      return (jsDate.getDate()<10?("0"+jsDate.getDate()):jsDate.getDate()) + "/" + 
          ((jsDate.getMonth()+1)<10?("0"+(jsDate.getMonth()+1)):(jsDate.getMonth()+1)) + "/" + 
          jsDate.getFullYear();
    }
    
    0 讨论(0)
  • 2020-11-22 03:26

    There is another approach to solve this problem, using slice in JavaScript.

    var d = new Date();
    var datestring = d.getFullYear() + "-" + ("0"+(d.getMonth()+1)).slice(-2) +"-"+("0" + d.getDate()).slice(-2);
    
    

    the datestring return date with format as you expect: 2019-09-01

    another approach is using dateformat library: https://github.com/felixge/node-dateformat

    0 讨论(0)
  • 2020-11-22 03:26

    Add some padding to allow a leading zero - where needed - and concatenate using your delimiter of choice as string.

    Number.prototype.padLeft = function(base,chr){
            var  len = (String(base || 10).length - String(this).length)+1;
            return len > 0? new Array(len).join(chr || '0')+this : this;
        }
    
    var d = new Date(my_date);
    var dformatted = [(d.getMonth()+1).padLeft(), d.getDate().padLeft(), d.getFullYear()].join('/');
    
    0 讨论(0)
  • 2020-11-22 03:27

    You could simply use :

    const d = new Date();
    const day = `0${d.getDate()}`.slice(-2);
    

    So a function could be created like :

    AddZero(val){
        // adding 0 if the value is a single digit
        return `0${val}`.slice(-2);
    }
    

    Your new code :

    var MyDate = new Date();
    var MyDateString = new Date();
    
    MyDate.setDate(MyDate.getDate()+10);
    MyDateString = AddZero(MyDate.getDate()) + '/' + AddZero(MyDate.getMonth() + 1) + '/' + MyDate.getFullYear();
    
    0 讨论(0)
  • 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"
    
    0 讨论(0)
提交回复
热议问题