Javascript date - Leading 0 for days and months where applicable

前端 未结 9 2024
情话喂你
情话喂你 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:36
    var myDate = new Date();
    var m = myDate.getMonth() + 1;
    var d = myDate.getDate();
    m = m > 9 ? m : "0"+m;
    d = d > 9 ? d : "0"+d;
    var prettyDate =(myDate.getFullYear() +'-'+ m) +'-'+ d;
    

    ...and a sample: http://jsfiddle.net/gFkaP/

    0 讨论(0)
  • 2020-12-15 05:36

    For Month, var month = ("0" + (myDate.getMonth() + 1)).slice(-2);

    For Day, var day = ("0" + (myDate.getDate() + 1)).slice(-2);

    0 讨论(0)
  • 2020-12-15 05:40

    You will have to manually check if it needs a leading zero and add it if necessary...

    var m = myDate.getMonth();
    var d =  myDate.getDate();
    
    if (m < 10) {
        m = '0' + m
    }
    
    if (d < 10) {
        d = '0' + d
    }
    
    var prettyDate = myDate.getFullYear() +'-'+ m +'-'+ d;
    
    0 讨论(0)
  • 2020-12-15 05:42

    The format you seem to want looks like ISO. So take advantage of toISOString():

    var d = new Date();
    var date = d.toISOString().slice(0,10); // "2014-05-12"
    
    0 讨论(0)
  • 2020-12-15 05:46

    Unfortunately there's no built-in date-format in javascript. Either use a existing library (example http://blog.stevenlevithan.com/archives/date-time-format) or build your own method for adding a leading zero.

    var addLeadingZeroIfNeeded = function addLeadingZeroIfNeeded(dateNumber) {
            if (String(dateNumber).length === 1) {
                return '0' + String(dateNumber);
            }
    
            return String(dateNumber);
        },
        myDate = new Date(),
        prettyDate;
    
    prettyDate = myDate.getFullYear() + '-' + addLeadingZeroIfNeeded(myDate.getMonth()) + '-' + addLeadingZeroIfNeeded(myDate.getDate());
    

    EDIT

    As Alnitak said, keep in mind that month i JavaScript starts on 0 not 1.

    0 讨论(0)
  • 2020-12-15 05:51

    You can try like this

    For day:

    ("0" + new Date().getDate()).slice(-2)
    

    For month:

    ("0" + (new Date().getMonth() + 1)).slice(-2)
    

    For year:

    new Date().getFullYear();
    
    0 讨论(0)
提交回复
热议问题