How do I format a Javascript Date?

后端 未结 11 1507
没有蜡笔的小新
没有蜡笔的小新 2020-12-03 07:55

How do I format this date so that the alert displays the date in MM/dd/yyyy format?



        
相关标签:
11条回答
  • 2020-12-03 08:29

    Just another option:

    DP_DateExtensions Library

    Not saying it's any better than the other options, but I like it (of course I'm not completely unbiased).

    0 讨论(0)
  • 2020-12-03 08:34

    A simple format would be:

    var d = new Date() // Thu Jun 30 2016 12:50:43 GMT-0500 (Central Daylight Time (Mexico))
    d.toJSON(); // "2016-06-30T17:50:43.084Z"
    
    0 讨论(0)
  • 2020-12-03 08:38

    You Could try:

    date = new Date().toLocaleDateString().split("/")
    date[0].length == 1 ? "0" + date[0] : date[0]
    date[1].length == 1 ? "0" + date[1] : date[1]
    date = date[0] + "/" + date[1] + "/" + date[2]
    
    0 讨论(0)
  • 2020-12-03 08:39

    You have to get old school on it:

    Date.prototype.toMMddyyyy = function() {
    
        var padNumber = function(number) {
    
            number = number.toString();
    
            if (number.length === 1) {
                return "0" + number;
            }
            return number;
        };
    
        return padNumber(date.getMonth() + 1) + "/" 
             + padNumber(date.getDate()) + "/" + date.getFullYear();
    };
    
    0 讨论(0)
  • 2020-12-03 08:39

    With a proper library you could internationalize your app for the whole world with just a few lines of code. By default it automatically localizes the date for the browser locale, but you can also define your own patterns:

    dojo.date.locale.format(
      new Date(2007,2,23,6,6,6),
      {datePattern: "yyyy-MM-dd", selector: "date"}
    );
    // yields: "2007-03-23"
    

    From: Formatting dates and times using custom patterns

    0 讨论(0)
  • 2020-12-03 08:47

    add Jquery Ui plugin to your page

    alert($.datepicker.formatDate('dd M yy', new Date()));
    
    0 讨论(0)
提交回复
热议问题