【问题标题】:How do I format a Javascript Date?如何格式化 Javascript 日期?
【发布时间】:2009-06-12 13:32:28
【问题描述】:

如何设置此日期的格式,以便警报以 MM/dd/yyyy 格式显示日期?

<script type="text/javascript">
   var date = new Date();
   alert(date);
</script>

【问题讨论】:

    标签: javascript date


    【解决方案1】:

    您制作了一个方法的原型,这样您就不必再做这个烦人的任务了:

    Date.prototype.toFormattedString = function (f)
    {
        var nm = this.getMonthName();
        var nd = this.getDayName();
        f = f.replace(/yyyy/g, this.getFullYear());
        f = f.replace(/yy/g, String(this.getFullYear()).substr(2,2));
        f = f.replace(/MMM/g, nm.substr(0,3).toUpperCase());
        f = f.replace(/Mmm/g, nm.substr(0,3));
        f = f.replace(/MM\*/g, nm.toUpperCase());
        f = f.replace(/Mm\*/g, nm);
        f = f.replace(/mm/g, String(this.getMonth()+1).padLeft('0',2));
        f = f.replace(/DDD/g, nd.substr(0,3).toUpperCase());
        f = f.replace(/Ddd/g, nd.substr(0,3));
        f = f.replace(/DD\*/g, nd.toUpperCase());
        f = f.replace(/Dd\*/g, nd);
        f = f.replace(/dd/g, String(this.getDate()).padLeft('0',2));
        f = f.replace(/d\*/g, this.getDate());
        return f;
    };
    

    (是的,您可以将这些替换链接起来,但在有人问之前,它并不是为了可读性)


    根据要求,支持上述 sn-p 的其他原型。

    Date.prototype.getMonthName = function ()
    {
        return this.toLocaleString().replace(/[^a-z]/gi,'');
    };
    
    //n.b. this is sooo not i18n safe :)
    Date.prototype.getDayName = function ()
    {
        switch(this.getDay())
        {
            case 0: return 'Sunday';
            case 1: return 'Monday';
            case 2: return 'Tuesday';
            case 3: return 'Wednesday';
            case 4: return 'Thursday';
            case 5: return 'Friday';
            case 6: return 'Saturday';
        }
    };
    
    String.prototype.padLeft = function (value, size) 
    {
        var x = this;
        while (x.length < size) {x = value + x;}
        return x;
    };
    

    及用法示例:

    alert((new Date()).toFormattedString('dd Mmm, yyyy'));
    

    【讨论】:

    • 此代码依赖于 Date.getMonthName()、Date.getDayName() 和 String.padLeft() 的原型。如果你也提供了这些实现,这个 sn-p 可能对人们更有用。
    • 另一个很棒的实现(如果你喜欢 PHP 的 date() 函数)在这里:jacwright.com/projects/javascript/date_format
    • @Kevin - 及时提供,但我想指出我的意图是建议“这是应该这样做的”,而不是“请使用此代码”:)
    • getMonthName 的解析方式在某些语言环境中搞砸了,导致奇怪的输出,例如 Mm* = WedSep
    【解决方案2】:

    你必须了解它:

    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();
    };
    

    【讨论】:

      【解决方案3】:

      将 Jquery Ui 插件添加到您的页面

      alert($.datepicker.formatDate('dd M yy', new Date()));
      

      【讨论】:

        【解决方案4】:

        你从微软优秀的 .toFormattedString 函数中提取出来,现在遗憾地错过了 atlas 库:

        Date.prototype.toFormattedString = function (format) {
            var dtf = Sys.CultureInfo.DateTimeFormat;
        
            if (!format)
                format = "F";
        
            if (format.length == 1) {
                switch (format) {
                    case "d":
                        format = dtf.ShortDatePattern;
                        break;
                    case "D":
                        format = dtf.LongDatePattern;
                        break;
                    case "t":
                        format = dtf.ShortTimePattern;
                        break;
                    case "T":
                        format = dtf.LongTimePattern;
                        break;
                    case "F":
                        format = dtf.FullDateTimePattern;
                        break;
                    case "M": case "m":
                        format = dtf.MonthDayPattern;
                        break;
                    case "s":
                        format = dtf.SortableDateTimePattern;
                        break;
                    case "Y": case "y":
                        format = dtf.YearMonthPattern;
                        break;
                    default:
                        throw Error.createError("'" + format + "' is not a valid date format");
                }
            }
        
            var regex = /dddd|ddd|dd|d|MMMM|MMM|MM|M|yyyy|yy|y|hh|h|HH|H|mm|m|ss|s|tt|t|fff|ff|f|zzz|zz|z/g;
        
            var ret = "";
            var hour;
        
            function addLeadingZero(num) {
                if (num < 10) {
                    return '0' + num;
                }
                return num.toString();
            }
        
            function addLeadingZeros(num) {
                if (num < 10) {
                    return '00' + num;
                }
                if (num < 100) {
                    return '0' + num;
                }
                return num.toString();
            }
        
            for (; ; ) {
        
                var index = regex.lastIndex;
        
                var ar = regex.exec(format);
        
                ret += format.slice(index, ar ? ar.index : format.length);
        
                if (!ar) break;
        
                switch (ar[0]) {
                    case "dddd":
                        ret += dtf.DayNames[this.getDay()];
                        break;
                    case "ddd":
                        ret += dtf.AbbreviatedDayNames[this.getDay()];
                        break;
                    case "dd":
                        ret += addLeadingZero(this.getDate());
                        break;
                    case "d":
                        ret += this.getDate();
                        break;
                    case "MMMM":
                        ret += dtf.MonthNames[this.getMonth()];
                        break;
                    case "MMM":
                        ret += dtf.AbbreviatedMonthNames[this.getMonth()];
                        break;
                    case "MM":
                        ret += addLeadingZero(this.getMonth() + 1);
                        break;
                    case "M":
                        ret += this.getMonth() + 1;
                        break;
                    case "yyyy":
                        ret += this.getFullYear();
                        break;
                    case "yy":
                        ret += addLeadingZero(this.getFullYear() % 100);
                        break;
                    case "y":
                        ret += this.getFullYear() % 100;
                        break;
                    case "hh":
                        hour = this.getHours() % 12;
                        if (hour == 0) hour = 12;
                        ret += addLeadingZero(hour);
                        break;
                    case "h":
                        hour = this.getHours() % 12;
                        if (hour == 0) hour = 12;
                        ret += hour;
                        break;
                    case "HH":
                        ret += addLeadingZero(this.getHours());
                        break;
                    case "H":
                        ret += this.getHours();
                        break;
                    case "mm":
                        ret += addLeadingZero(this.getMinutes());
                        break;
                    case "m":
                        ret += this.getMinutes();
                        break;
                    case "ss":
                        ret += addLeadingZero(this.getSeconds());
                        break;
                    case "s":
                        ret += this.getSeconds();
                        break;
                    case "tt":
                        ret += (this.getHours() < 12) ? dtf.AMDesignator : dtf.PMDesignator;
                        break;
                    case "t":
                        ret += ((this.getHours() < 12) ? dtf.AMDesignator : dtf.PMDesignator).charAt(0);
                        break;
                    case "f":
                        ret += addLeadingZeros(this.getMilliseconds()).charAt(0);
                        break;
                    case "ff":
                        ret += addLeadingZeros(this.getMilliseconds()).substr(0, 2);
                        break;
                    case "fff":
                        ret += addLeadingZeros(this.getMilliseconds());
                        break;
                    case "z":
                        hour = this.getTimezoneOffset() / 60;
                        ret += ((hour >= 0) ? '+' : '-') + Math.floor(Math.abs(hour));
                        break;
                    case "zz":
                        hour = this.getTimezoneOffset() / 60;
                        ret += ((hour >= 0) ? '+' : '-') + addLeadingZero(Math.floor(Math.abs(hour)));
                        break;
                    case "zzz":
                        hour = this.getTimezoneOffset() / 60;
                        ret += ((hour >= 0) ? '+' : '-') + addLeadingZero(Math.floor(Math.abs(hour))) +
                        dtf.TimeSeparator + addLeadingZero(Math.abs(this.getTimezoneOffset() % 60));
                        break;
                    default:
                        debug.assert(false);
                }
            }
            return ret;
        }
        

        【讨论】:

        • 任何其他可能有帮助的细节/解释?
        【解决方案5】:

        使用适当的库,您只需几行代码就可以将您的应用国际化,使其面向全世界。默认情况下,它会自动本地化浏览器区域设置的日期,但您也可以定义自己的模式:

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

        发件人:Formatting dates and times using custom patterns

        【讨论】:

          【解决方案6】:

          YUI 还提供对日期格式的支持,这在最近的一系列博客文章中都有介绍:

          【讨论】:

            【解决方案7】:

            一个简单的格式是:

            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"
            

            【讨论】:

            • 最简单的纯javascript答案!对于input type="date",可以使用d.toJSON().substr(0,10),对于input type="time",可以使用d.toJSON().substr(11,5)——当然,前提是需要GMT而不是当地时间
            【解决方案8】:

            只是另一种选择:

            DP_DateExtensions Library

            并不是说它比其他选项更好,但我喜欢它(当然我也不是完全没有偏见)。

            【讨论】:

              【解决方案9】:

              试试date.js,例如:

              <script type="text/javascript">
                 alert(new Date().toString('M/d/yyyy'));
              </script>
              

              【讨论】:

                【解决方案10】:

                你可以试试:

                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]
                

                【讨论】:

                  【解决方案11】:

                  2017年回答:使用moment.js

                  【讨论】:

                    猜你喜欢
                    • 2022-01-18
                    • 1970-01-01
                    • 1970-01-01
                    相关资源
                    最近更新 更多