如何格式化Javascript日期?

ScA*_*er2 13 javascript date

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

<script type="text/javascript">
   var date = new Date();
   alert(date);
</script>
Run Code Online (Sandbox Code Playgroud)

ann*_*ata 31

您对方法进行了原型设计,因此您再也不必执行这项烦人的任务:

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;
};
Run Code Online (Sandbox Code Playgroud)

(是的,你可以将这些替换链接起来,但在任何人要求之前,这里的可读性并不存在)


根据要求,支持上述代码段的其他原型.

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;
};
Run Code Online (Sandbox Code Playgroud)

和用法示例:

alert((new Date()).toFormattedString('dd Mmm, yyyy'));
Run Code Online (Sandbox Code Playgroud)

  • 此代码依赖于具有Date.getMonthName(),Date.getDayName()和String.padLeft()的原型.如果您还提供了这些实现,则此代码段可能对人们更有用. (5认同)
  • @Kevin - 正式提供,虽然我想注意我的意图是建议"这是应该怎么做",而不是"请使用此代码":) (3认同)

Gar*_*ler 7

你必须上学:

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();
};
Run Code Online (Sandbox Code Playgroud)