在哪里可以找到用javascript格式化日期的文档?

Where can I find documentation on formatting a date in JavaScript?

我注意到javascript的new Date()函数在接受多种格式的日期方面非常聪明。

1
2
3
Xmas95 = new Date("25 Dec, 1995 23:15:00")
Xmas95 = new Date("2009 06 12,12:52:39")
Xmas95 = new Date("20 09 2006,12:52:39")

调用new Date()函数时,在任何地方都找不到显示所有有效字符串格式的文档。

用于将字符串转换为日期。如果我们看的是另一面,也就是将日期对象转换为字符串,直到现在,我还认为JavaScript没有内置的API来将日期对象格式化为字符串。

Editor's note: The following approach is the asker's attempt that worked on a particular browser but does not work in general; see the answers on this page to see some actual solutions.

今天,我在日期对象上使用了toString()方法,令人惊讶的是,它用于将日期格式化为字符串。

1
2
3
var d1 = new Date();
d1.toString('yyyy-MM-dd');       //Returns"2009-06-29" in Internet Explorer, but not Firefox or Chrome
d1.toString('dddd, MMMM ,yyyy')  //Returns"Monday, June 29,2009" in Internet Explorer, but not Firefox or Chrome

此外,在这里,我找不到任何有关如何将日期对象格式化为字符串的文档。

列出Date()对象支持的格式说明符的文档在哪里?


我喜欢使用javascript和使用日期的10种方式来格式化时间和日期。

基本上,您有三种方法,您必须为自己组合字符串:

1
2
3
getDate() // Returns the date
getMonth() // Returns the month
getFullYear() // Returns the year

例子:

1
2
3
4
5
var d = new Date();
var curr_date = d.getDate();
var curr_month = d.getMonth() + 1; //Months are zero based
var curr_year = d.getFullYear();
console.log(curr_date +"-" + curr_month +"-" + curr_year);


JS

它是一个(轻量级的)*javascript日期库,用于分析、操作和格式化日期。

1
2
3
var a = moment([2010, 1, 14, 15, 25, 50, 125]);
a.format("dddd, MMMM Do YYYY, h:mm:ss a"); //"Sunday, February 14th 2010, 3:25:50 pm"
a.format("ddd, hA");                       //"Sun, 3PM"

(*)轻量级意味着9.3kb小型化+gzip以尽可能小的设置(2014年2月)


如果您已经在项目中使用jquery用户界面,则可以使用内置的datepicker方法来格式化日期对象:

1
$.datepicker.formatDate('yy-mm-dd', new Date(2007, 1 - 1, 26));

但是,日期选取器只格式化日期,不能格式化时间。

看看jquery ui-datepicker-formatdate,例子。


Where is the documentation which lists the format specifiers supported by the Date() object?

今天我偶然发现了这个问题,很惊讶没有人花时间回答这个简单的问题。确实,有很多库可以帮助处理日期。有些人比其他人好。但这不是问题所在。

faik,纯javascript不支持格式说明符,因为您已经表示希望使用它们。但它支持格式化日期和/或时间的方法,如.toLocaleDateString().toLocaleTimeString().toUTCString()

我最常使用的Date对象引用位于w3schools.com网站上(但快速的谷歌搜索将显示更多更好地满足您需求的内容)。

另外请注意,日期对象属性部分提供了一个指向prototype的链接,该链接说明了使用自定义方法扩展日期对象的一些方法。多年来,JavaScript社区一直在争论这是否是最佳实践,我不赞成也不反对,只是指出它的存在。


自定义格式设置函数:

对于固定格式,只需一个简单的函数即可完成任务。以下示例生成国际格式YYYY-MM-DD:

1
2
3
4
5
6
function dateToYMD(date) {
    var d = date.getDate();
    var m = date.getMonth() + 1;
    var y = date.getFullYear();
    return '' + y + '-' + (m<=9 ? '0' + m : m) + '-' + (d <= 9 ? '0' + d : d);
}

注意:但是,扩展JavaScript标准库通常不是一个好主意(例如,通过将此函数添加到日期原型中)。

更高级的函数可以根据格式参数生成可配置的输出。在同一页中有几个很好的例子。

如果编写格式化函数的时间太长,则周围有很多库可以执行此操作。其他一些答案已经列举出来了。但是依赖性的增加也有它的反作用。

标准ECMAScript格式化函数:

由于ecmascript的更新版本,Date类具有一些特定的格式化功能:

toDateString: Implementation dependent, show only the date.

http://www.ecma-international.org/ecma-262/7.0/index.html#sec-date.prototype.todatestring

1
new Date().toDateString(); // e.g."Fri Nov 11 2016"

toISOString: Show ISO 8601 date and time.

http://www.ecma-international.org/ecma-262/7.0/index.html#sec-date.prototype.toisostring

1
new Date().toISOString(); // e.g."2016-11-21T08:00:00.000Z"

toJSON: Stringifier for JSON.

http://www.ecma-international.org/ecma-262/7.0/index.html#sec-date.prototype.tojson

1
new Date().toJSON(); // e.g."2016-11-21T08:00:00.000Z"

toLocaleDateString: Implementation dependent, a date in locale format.

http://www.ecma-international.org/ecma-262/7.0/index.html#sec-date.prototype.tolocaledatestring

1
new Date().toLocaleDateString(); // e.g."21/11/2016"

toLocaleString: Implementation dependent, a date&time in locale format.

http://www.ecma-international.org/ecma-262/7.0/index.html#sec-date.prototype.tolocalestring

1
new Date().toLocaleString(); // e.g."21/11/2016, 08:00:00 AM"

toLocaleTimeString: Implementation dependent, a time in locale format.

http://www.ecma-international.org/ecma-262/7.0/index.html#sec-date.prototype.tolocaletimestring

1
new Date().toLocaleTimeString(); // e.g."08:00:00 AM"

toString: Generic toString for Date.

http://www.ecma-international.org/ecma-262/7.0/index.html#sec-date.prototype.tostring

1
new Date().toString(); // e.g."Fri Nov 11 2016 08:00:00 GMT+0100 (W. Europe Standard Time)"

注意:可以使用这些格式化函数生成自定义输出:

1
new Date().toISOString().slice(0,10); // By @Image72, return YYYY-MM-DD


简短的回答

Javascript不提供"通用"文档;每个拥有Javascript的浏览器实际上都是一个实现。但是,大多数现代浏览器都会遵循一个标准,这就是emcascript标准;ecmascript标准字符串至少需要修改iso 8601定义的实现。好的。

除此之外,IETF还制定了第二个标准,供浏览器使用,这是RFC2822中对时间戳的定义。实际文档可在底部的参考列表中找到。好的。

从这一点上,您可以期望基本的功能,但是"应该"的本质上并不是"应该"的。不过,我将对这个程序进行一点深入的探讨,因为似乎只有三个人真正回答了这个问题(斯科特、古夫堡逻辑和佩勒,也就是说),对我来说,这意味着大多数人不知道当你创建一个日期对象时实际发生了什么。好的。


长的答案

Where is the documentation which lists the format specifiers supported by the Date() object?

Ok.

< BR>好的。

要回答这个问题,或者通常寻找这个问题的答案,您需要知道javascript不是一种新颖的语言;它实际上是ecmascript的一种实现,并遵循ecmascript标准(但请注意,javascript实际上也预先制定了这些标准;emcascript标准是在早期实现livescript/javascript)。目前的ECMAScript标准是5.1(2011年);在最初提出问题的时候(2009年6月),标准是3(4被放弃),但5在2009年底发布后不久发布。这应该概括出一个问题:JavaScript实现可能遵循的标准,可能不反映实际到位的标准,因为a)它是给定标准的实现,b)并非所有标准的实现都是清教徒的,c)功能没有与新标准同步发布,因为d)实现是一个正在进行的阶段性工作好的。

本质上,在处理JavaScript时,您要处理的是实现(JavaScript本身)的派生(特定于浏览器的JavaScript)。例如,Google的V8实现了ECMAScript 5.0,但Internet Explorer的JScript并不试图符合任何ECMAScript标准,而Internet Explorer 9则符合ECMAScript 5.0。好的。

当将单个参数传递给new date()时,它将强制转换此函数原型:好的。

1
new Date(value)

当两个或多个参数传递给new date()时,它将强制转换此函数原型:好的。

1
new Date (year, month [, date [, hours [, minutes [, seconds [, ms ] ] ] ] ] )

< BR>这两个函数看起来都应该很熟悉,但这并不能立即回答您的问题,而什么量化作为可接受的"日期格式"需要进一步的解释。当您将一个字符串传递给new date()时,它将为新日期(value)调用原型(请注意,我松散地使用了单词prototype;版本可能是单个函数,或者它可能是单个函数中条件语句的一部分),并将您的字符串作为"value"参数的参数。此函数将首先检查它是数字还是字符串。此功能的文档可在以下位置找到:好的。

http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.3.2

Ok.

由此,我们可以推断,要获得新日期(值)允许的字符串格式,我们必须查看方法date.parse(字符串)。此方法的文档可在以下位置找到:好的。

http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.4.2

Ok.

我们还可以进一步推断日期应采用修改后的ISO 8601扩展格式,如下所述:好的。< Buff行情>

http://www.ecma-international.org/ecma-262/5.1/sec-15.9.1.15好的。< /块引用>

但是,我们可以从经验中认识到,javascript的日期对象接受其他格式(首先由这个问题的存在强制执行),这是可以的,因为ecmascript允许实现特定的格式。但是,这仍然不能回答关于可用格式上可用的文档以及实际允许的格式的问题。我们将看看Google的javascript实现,V8;请注意,我不是建议这是"最好的"javascript引擎(如何定义"最好的"甚至"好的"),我们不能假设V8中允许的格式代表了今天所有可用的格式,但我认为假设它们确实遵循现代的预期是公平的。ONS。好的。

Google’s V8, date.js, DateConstructor

Ok.

https://code.google.com/p/v8/source/browse/trunk/src/date.js?r=18400#141

Ok.

查看dateconstructor函数,我们可以推断我们需要找到dateparse函数;但是,请注意,"year"不是实际年份,只是对"year"参数的引用。好的。

Google’s V8, date.js, DateParse

Ok.

https://code.google.com/p/v8/source/browse/trunk/src/date.js?r=18400#270

Ok.

这调用%DATEPARSESCOPE,这实际上是C++函数的运行时函数引用。参考以下代码:好的。

Google’s V8, runtime.cc, %DateParseString

Ok.

https://code.google.com/p/v8/source/browse/trunk/src/runtime.cc?r=18400#9559

Ok.

我们在函数中关注的函数调用是针对dateparser::parse();忽略这些函数调用周围的逻辑,这些只是检查是否符合编码类型(ascii和uc16)。这里定义了dateparser::parse:好的。

Google's V8, dateparser-inl.h, DateParser::Parse

Ok.

https://code.google.com/p/v8/source/browse/trunk/src/dateparser-inl.h?r=18400#36

Ok.

这个函数实际上定义了它接受的格式。本质上,它检查emcascript 5.0 ISO 8601标准,如果它不符合标准,那么它将尝试基于旧格式构建日期。基于评论的几个要点:好的。

  • 解析程序未知的第一个数字之前的单词将被忽略。
  • 忽略带括号的文本。
  • 后跟":"的无符号数字被解释为"时间组件"。
  • 后面跟"."的无符号数字被解释为"时间组件",后面必须跟毫秒。
  • 带符号的数字后接小时或小时分钟(例如+5:15或+0515)被解释为时区。
  • 在声明小时和分钟时,可以使用"hh:mm"或"hh mm"。
  • 表示时区的词被解释为时区。
  • 所有其他数字都被解释为"日期组成部分"。
  • 所有以月份前三位数字开头的单词都被解释为月份。
  • 您可以用以下两种格式之一定义分钟和小时:"hh:mm"或"hh mm"。
  • 处理完数字后,不允许使用"+"、"-"和"unmatched")"等符号。
  • 符合多种格式(如1970-01-01)的项目将作为符合标准的emcascript 5.0 iso 8601字符串进行处理。
  • 因此,这应该足以让您对向日期对象传递字符串有一个基本的了解。您可以通过查看Mozilla在Mozilla开发人员网络上指向的以下规范(符合IETF RFC 2822时间戳)来进一步扩展这一点:好的。

    http://tools.ietf.org/html/rfc2822#page-14

    Ok.

    Microsoft Developer Network还提到了日期对象的附加标准:ECMA-402,ECMAScript国际化API规范,它是对ECMAScript 5.1标准(以及未来的标准)的补充。可以在这里找到:好的。< Buff行情>

    http://www.ecma-international.org/ecma-402/1.0/好的。< /块引用>

    在任何情况下,这都有助于突出显示没有普遍表示所有JavaScript实现的"文档",但是仍然有足够的文档可用于合理理解日期对象可接受的字符串。当你想到这个问题的时候,你会问很多问题,是吗?P好的。

    References

    Ok.

    http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.3.2

    Ok.

    http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.4.2

    Ok.

    http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.1.15

    Ok.

    http://tools.ietf.org/html/rfc2822#page-14

    Ok.

    http://www.ecma-international.org/ecma-402/1.0/

    Ok.

    https://code.google.com/p/v8/source/browse/trunk/src/date.js?r=18400#141

    Ok.

    https://code.google.com/p/v8/source/browse/trunk/src/date.js?r=18400#270

    Ok.

    https://code.google.com/p/v8/source/browse/trunk/src/runtime.cc?r=18400#9559

    Ok.

    https://code.google.com/p/v8/source/browse/trunk/src/dateparser-inl.h?r=18400#36

    Ok.

    Resources

    Ok.

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

    Ok.

    http://msdn.microsoft.com/en-us/library/ff743760(v=vs.94).aspx

    Ok.

    好啊。


    在处理javascript中的日期时,请确保签出datejs。它非常令人印象深刻,并且有很好的文档记录,正如您在ToString函数中看到的那样。

    编辑:泰勒·福塞思指出,日期已经过时了。我在我当前的项目中使用它,并没有遇到任何问题,但是您应该意识到这一点并考虑替代方案。


    如Meizz所述,只需使用新的format方法扩展Date对象,下面是作者给出的代码。和这是一把J小提琴。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    Date.prototype.format = function(format) //author: meizz
    {
      var o = {
       "M+" : this.getMonth()+1, //month
       "d+" : this.getDate(),    //day
       "h+" : this.getHours(),   //hour
       "m+" : this.getMinutes(), //minute
       "s+" : this.getSeconds(), //second
       "q+" : Math.floor((this.getMonth()+3)/3),  //quarter
       "S" : this.getMilliseconds() //millisecond
      }

      if(/(y+)/.test(format)) format=format.replace(RegExp.$1,
        (this.getFullYear()+"").substr(4 - RegExp.$1.length));
      for(var k in o)if(new RegExp("("+ k +")").test(format))
        format = format.replace(RegExp.$1,
          RegExp.$1.length==1 ? o[k] :
            ("00"+ o[k]).substr((""+ o[k]).length));
      return format;
    }

    alert(new Date().format("yyyy-MM-dd"));
    alert(new Date("january 12 2008 11:12:30").format("yyyy-MM-dd h:mm:ss"));


    您引用的功能不是标准的JavaScript,不太可能在浏览器之间移植,因此不是很好的实践。ECMAScript 3规范将解析和输出格式的功能留给JavaScript实现。ECMAScript 5添加了ISO8601支持的一个子集。我相信您提到的toString()函数是一个浏览器(mozilla)的创新。

    一些库提供了参数化这一点的例程,有些库提供了广泛的本地化支持。您还可以在dojo.date.locale中查看这些方法。


    我做了一个非常简单的格式化程序,它是Cut/N/Pastable(更新为Neater版本):

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    function DateFmt(fstr) {
      this.formatString = fstr

      var mthNames = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
      var dayNames = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];
      var zeroPad = function(number) {
         return ("0"+number).substr(-2,2);
      }

      var dateMarkers = {
        d:['getDate',function(v) { return zeroPad(v)}],
        m:['getMonth',function(v) { return zeroPad(v+1)}],
        n:['getMonth',function(v) { return mthNames[v]; }],
        w:['getDay',function(v) { return dayNames[v]; }],
        y:['getFullYear'],
        H:['getHours',function(v) { return zeroPad(v)}],
        M:['getMinutes',function(v) { return zeroPad(v)}],
        S:['getSeconds',function(v) { return zeroPad(v)}],
        i:['toISOString']
      };

      this.format = function(date) {
        var dateTxt = this.formatString.replace(/%(.)/g, function(m, p) {
          var rv = date[(dateMarkers[p])[0]]()

          if ( dateMarkers[p][1] != null ) rv = dateMarkers[p][1](rv)

          return rv

        });

        return dateTxt
      }

    }

    fmt = new DateFmt("%w %d:%n:%y - %H:%M:%S  %i")
    v = fmt.format(new Date())

    http://snipplr.com/view/66968.82825/


    无框架,有限但轻

    1
    2
    3
    4
    5
    var d = (new Date()+'').split(' ');
    // ["Tue","Sep","03","2013","21:54:52","GMT-0500","(Central","Daylight","Time)"]

    [d[3], d[1], d[2], d[4]].join(' ');
    //"2013 Sep 03 21:58:03"


    DateJS当然是全功能的,但是我建议使用更简单的lib(javascript日期格式),我更喜欢这种格式,因为它只有120行左右。


    在研究了其他答案中提供的几个选项后,我决定编写自己的有限但简单的解决方案,其他人可能也会发现它是有用的。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    /**
    * Format date as a string
    * @param date - a date object (usually"new Date();")
    * @param format - a string format, eg."DD-MM-YYYY"
    */

    function dateFormat(date, format) {
        // Calculate date parts and replace instances in format string accordingly
        format = format.replace("DD", (date.getDate() < 10 ? '0' : '') + date.getDate()); // Pad with '0' if needed
        format = format.replace("MM", (date.getMonth() < 9 ? '0' : '') + (date.getMonth() + 1)); // Months are zero-based
        format = format.replace("YYYY", date.getFullYear());
        return format;
    }

    示例用法:

    1
    console.log("The date is:" + dateFormat(new Date(),"DD/MM/YYYY"));


    这是我经常使用的功能。结果是yyyy-mm-dd hh:mm:ss.nnn。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    function date_and_time() {
        var date = new Date();
        //zero-pad a single zero if needed
        var zp = function (val){
            return (val <= 9 ? '0' + val : '' + val);
        }

        //zero-pad up to two zeroes if needed
        var zp2 = function(val){
            return val <= 99? (val <=9? '00' + val : '0' + val) : ('' + val ) ;
        }

        var d = date.getDate();
        var m = date.getMonth() + 1;
        var y = date.getFullYear();
        var h = date.getHours();
        var min = date.getMinutes();
        var s = date.getSeconds();
        var ms = date.getMilliseconds();
        return '' + y + '-' + zp(m) + '-' + zp(d) + ' ' + zp(h) + ':' + zp(min) + ':' + zp(s) + '.' + zp2(ms);
    }


    您可能会发现对日期对象的这种修改很有用,它比任何库都小,并且很容易扩展以支持不同的格式:

    注:

    • 它使用在旧浏览器中未定义的object.keys(),因此可能需要从给定链接实现polyfill。

    代码

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    Date.prototype.format = function(format) {
        // set default format if function argument not provided
        format = format || 'YYYY-MM-DD hh:mm';

        var zeropad = function(number, length) {
                number = number.toString();
                length = length || 2;
                while(number.length < length)
                    number = '0' + number;
                return number;
            },
            // here you can define your formats
            formats = {
                YYYY: this.getFullYear(),
                MM: zeropad(this.getMonth() + 1),
                DD: zeropad(this.getDate()),
                hh: zeropad(this.getHours()),
                mm: zeropad(this.getMinutes())
            },
            pattern = '(' + Object.keys(formats).join(')|(') + ')';

        return format.replace(new RegExp(pattern, 'g'), function(match) {
            return formats[match];
        });
    };

    使用

    1
    2
    3
    4
    5
    6
    var now = new Date;
    console.log(now.format());
    // outputs: 2015-02-09 11:47
    var yesterday = new Date('2015-02-08');
    console.log(yesterday.format('hh:mm YYYY/MM/DD'));
    // outputs: 00:00 2015/02/08

    只是为了继续龚智涛的可靠回答-这个处理上午/下午

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
     Date.prototype.format = function (format) //author: meizz
    {
        var hours = this.getHours();
        var ttime ="AM";
        if(format.indexOf("t") > -1 && hours > 12)
        {
            hours = hours - 12;
            ttime ="PM";
         }

    var o = {
       "M+": this.getMonth() + 1, //month
       "d+": this.getDate(),    //day
       "h+": hours,   //hour
       "m+": this.getMinutes(), //minute
       "s+": this.getSeconds(), //second
       "q+": Math.floor((this.getMonth() + 3) / 3),  //quarter
       "S": this.getMilliseconds(), //millisecond,
       "t+": ttime
    }

    if (/(y+)/.test(format)) format = format.replace(RegExp.$1,
      (this.getFullYear() +"").substr(4 - RegExp.$1.length));
    for (var k in o) if (new RegExp("(" + k +")").test(format))
        format = format.replace(RegExp.$1,
          RegExp.$1.length == 1 ? o[k] :
            ("00" + o[k]).substr(("" + o[k]).length));
    return format;
    }


    我找不到任何关于有效日期格式的最终文档,所以我编写了自己的测试来查看各种浏览器支持什么。

    http://blarg.co.uk/blog/javascript-date-格式

    我的结果得出以下格式在我测试的所有浏览器中都有效(示例使用日期"2013年8月9日"):

    [全年]/[月份]/[日期编号]-月份可以是带或不带前导零的数字,也可以是短格式或长格式的月份名称,日期编号可以带或不带前导零。

    • 2013/08/09
    • 2013/08/9
    • 2013/8/09
    • 2013/8/9
    • 2013 /八月/ 09
    • 2013 /八月/ 9
    • 2013 /八月/ 09日
    • 2013 /八月/ 9日

    [月份]/[全年]/[日期编号]-月份可以是带或不带前导零的数字,也可以是短格式或长格式的月份名称,日期编号可以带或不带前导零。

    • 08/2013/09
    • 08/2013/9
    • 8/2013/09
    • 8/2013/9
    • 八月/ 2013/09
    • 八月/ 2013/9日
    • 八月/ 2013日/ 09日
    • 八月2013/9日

    用空格分隔的[全年]、[月份名称]和[日期编号]的任意组合-月份名称可以是短格式或长格式,日期编号可以带或不带前导零。

    • 2013八月09
    • 2013年8月09
    • 09 2013年8月
    • 2013八月09
    • 8月9日2013
    • 2013 9欧格
    • 等。。。

    也适用于"现代浏览器"(或者换句话说,除IE9及以下版本外的所有浏览器)

    [全年]-[月份号]-[日期号]-月份和日期号必须包含前导零(这是MySQL日期类型使用的格式)

    • 2013-08-09

    使用月份名称:有趣的是,当使用月份名称时,我发现只使用了月份名称的前3个字符,因此以下所有字符都是完全有效的:

    1
    2
    3
    4
    new Date('9 August 2013');
    new Date('9 Aug 2013');
    new Date('9 Augu 2013');
    new Date('9 Augustagfsdgsd 2013');

    在javascript中格式化,尤其是解析日期可能有点让人头疼。并非所有浏览器都以相同的方式处理日期。因此,虽然了解基本方法很有用,但使用助手库更为实用。

    AdamShaw的xdate javascript库从2011年中期就已经存在,目前仍在积极开发中。它有出色的文档、出色的API、格式化,试图保持向后兼容,甚至支持本地化字符串。

    更改区域设置字符串的链接:https://gist.github.com/1221376


    示例代码:

    1
    2
    var d = new Date();
    var time = d.toISOString().replace(/.*?T(\d+:\d+:\d+).*/,"$1");

    输出:

    "13:45:20"


    sugar.js库有一些在javascript中处理日期的强大功能。而且它有很好的文档记录。

    Sugar gives the Date class much love starting with the Date.create
    method which can understand dates in just about any format in 15 major
    languages, including relative formats like"1 hour ago". Dates can
    also be output in any format or language using an easy to understand
    syntax, with shortcuts to commonly used date formats. Complex date
    comparison is also possible with methods like is, which understand any
    format and apply built in precision.

    举几个例子:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    Date.create('July 4, 1776')  -> July 4, 1776
    Date.create(-446806800000)   -> November 5, 1955
    Date.create(1776, 6, 4)      -> July 4, 1776
    Date.create('1776年07月04日', 'ja') -> July 4, 1776
    Date.utc.create('July 4, 1776', 'en')  -> July 4, 1776

    Date.create().format('{Weekday} {d} {Month}, {yyyy}')    -> Monday July 4, 2003
    Date.create().format('{hh}:{mm}')                        -> 15:57
    Date.create().format('{12hr}:{mm}{tt}')                  -> 3:57pm
    Date.create().format(Date.ISO8601_DATETIME)              -> 2011-07-05 12:24:55.528Z

    Date.create().is('the 7th of June') -> false
    Date.create().addMonths(2); ->"Sunday, June 15, 2014 13:39"

    所有浏览器

    使用您使用的源格式格式化日期的最可靠方法是应用以下步骤:

  • 使用new Date()创建Date对象
  • .getDate().getMonth().getFullYear()分别得到日、月、年
  • 根据目标格式将这些片段粘贴在一起
  • 例子:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    var date = '2015-11-09T10:46:15.097Z';

    function format(input) {
        var date = new Date(input);
        return [
           ("0" + date.getDate()).slice(-2),
           ("0" + (date.getMonth()+1)).slice(-2),
           date.getFullYear()
        ].join('/');
    }

    document.body.innerHTML = format(date); // OUTPUT : 09/11/2015

    (另见这把小提琴)。

    仅限现代浏览器

    您还可以使用内置的.toLocaleDateString方法为您进行格式化。您只需要传递适当的区域设置和选项来匹配正确的格式,遗憾的是,只有现代浏览器(*)支持这种格式:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    var date = '2015-11-09T10:46:15.097Z';

    function format(input) {
        return new Date(input).toLocaleDateString('en-GB', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit'
        });
    }

    document.body.innerHTML = format(date); // OUTPUT : 09/11/2015

    (另见这把小提琴)。

    (*)根据MDN,"现代浏览器"是指Chrome 24+、Firefox 29+、IE11、Edge12+、Opera 15+、Safari Nightly Build。


    另一个选择,我写道:

    dp_日期扩展库

    不确定它是否有帮助,但我发现它在一些项目中很有用-看起来它可以满足您的需要。

    支持日期/时间格式、日期数学(加/减日期部分)、日期比较、日期分析等。它是自由开放的源代码。

    如果您已经在使用一个框架(它们都是有能力的),那么没有理由考虑它,但是如果您只需要快速地将日期操作添加到一个项目中,那么就给它一个机会。


    如果您只想用两位数字显示时间,这可能有助于您:

    1
    2
    3
    4
    5
    6
    var now = new Date();
    var cHour = now.getHours();
    var cMinuts = now.getMinutes();
    var cSeconds = now.getSeconds();

    var outStr = (cHour <= 0 ? ('0' + cHour) : cHour) + ':' + (cMinuts <= 9 ? ('0' + cMinuts) : cMinuts) + ':' + (cSeconds <= 9 ? '0' + cSeconds : cSeconds);

    格式化返回"2012-12-29"的日期的正确方法是使用javascript日期格式的脚本:

    1
    2
    var d1 = new Date();
    return d1.format("dd-m-yy");

    此代码不起作用:

    1
    2
    var d1 = new Date();
    d1.toString('yyyy-MM-dd');


    使用此功能

    1
    toTimeString() and toLocaleDateString()

    有关详细信息,请参阅以下链接https://developer.mozilla.org/en-us/docs/web/javascript/reference/global_对象/date


    答案是"无处可寻",因为日期格式是专有功能。我不认为toString函数是为了符合特定的格式。例如,在ECMAScript 5.1规范(http://www.ecma-international.org/publications/files/ecma-st/ecma-262.pdf,2/8/2013,第173页)中,ToString函数记录如下:

    "The contents of the String are implementation-dependent"

    下面的示例等函数可以很容易地用于完成格式化。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    function pad(toPad, padWith) {
        return (String(padWith) + String(toPad)).slice(-1 * padWith.length);
    }

    function dateAsInputValue(toFormat) {
        if(!(toFormat instanceof Date)) return null;
        return toFormat.getFullYear() +"-" + pad(toFormat.getMonth() + 1,"00") +"-" + pad(toFormat.getDate(),"00");
    }

    function timeAsInputValue(toFormat) {
        if(!(toFormat instanceof Date)) return null;        
        return pad(toFormat.getHours(),"00") +":" + pad(toFormat.getMinutes(),"00") +":" + pad(toFormat.getSeconds(),"00");
    }

    如果您不需要像moment.js这样的库提供的所有功能,那么您可以使用我的strftime端口。它很轻(与moment.js 2.15.0相比,1.35 kb与57.9 kb最小),并且提供了strftime()的大部分功能。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    /* Port of strftime(). Compatibility notes:
     *
     * %c - formatted string is slightly different
     * %D - not implemented (use"%m/%d/%y" or"%d/%m/%y")
     * %e - space is not added
     * %E - not implemented
     * %h - not implemented (use"%b")
     * %k - space is not added
     * %n - not implemented (use"
    ")
     * %O - not implemented
     * %r - not implemented (use"%I:%M:%S %p")
     * %R - not implemented (use"%H:%M")
     * %t - not implemented (use"\t")
     * %T - not implemented (use"%H:%M:%S")
     * %U - not implemented
     * %W - not implemented
     * %+ - not implemented
     * %% - not implemented (use"%")
     *
     * strftime() reference:
     * http://man7.org/linux/man-pages/man3/strftime.3.html
     *
     * Day of year (%j) code based on Joe Orost's answer:
     * http://stackoverflow.com/questions/8619879/javascript-calculate-the-day-of-the-year-1-366
     *
     * Week number (%V) code based on Taco van den Broek's prototype:
     * http://techblog.procurios.nl/k/news/view/33796/14863/calculate-iso-8601-week-and-year-in-javascript.html
     */

    function strftime(sFormat, date) {
      if (!(date instanceof Date)) date = new Date();
      var nDay = date.getDay(),
        nDate = date.getDate(),
        nMonth = date.getMonth(),
        nYear = date.getFullYear(),
        nHour = date.getHours(),
        aDays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
        aMonths = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
        aDayCount = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334],
        isLeapYear = function() {
          if (nYear&3!==0) return false;
          return nYear%100!==0 || year%400===0;
        },
        getThursday = function() {
          var target = new Date(date);
          target.setDate(nDate - ((nDay+6)%7) + 3);
          return target;
        },
        zeroPad = function(nNum, nPad) {
          return ('' + (Math.pow(10, nPad) + nNum)).slice(1);
        };
      return sFormat.replace(/%[a-z]/gi, function(sMatch) {
        return {
          '%a': aDays[nDay].slice(0,3),
          '%A': aDays[nDay],
          '%b': aMonths[nMonth].slice(0,3),
          '%B': aMonths[nMonth],
          '%c': date.toUTCString(),
          '%C': Math.floor(nYear/100),
          '%d': zeroPad(nDate, 2),
          '%e': nDate,
          '%F': date.toISOString().slice(0,10),
          '%G': getThursday().getFullYear(),
          '%g': ('' + getThursday().getFullYear()).slice(2),
          '%H': zeroPad(nHour, 2),
          '%I': zeroPad((nHour+11)%12 + 1, 2),
          '%j': zeroPad(aDayCount[nMonth] + nDate + ((nMonth>1 && isLeapYear()) ? 1 : 0), 3),
          '%k': '' + nHour,
          '%l': (nHour+11)%12 + 1,
          '%m': zeroPad(nMonth + 1, 2),
          '%M': zeroPad(date.getMinutes(), 2),
          '%p': (nHour<12) ? 'AM' : 'PM',
          '%P': (nHour<12) ? 'am' : 'pm',
          '%s': Math.round(date.getTime()/1000),
          '%S': zeroPad(date.getSeconds(), 2),
          '%u': nDay || 7,
          '%V': (function() {
                  var target = getThursday(),
                    n1stThu = target.valueOf();
                  target.setMonth(0, 1);
                  var nJan1 = target.getDay();
                  if (nJan1!==4) target.setMonth(0, 1 + ((4-nJan1)+7)%7);
                  return zeroPad(1 + Math.ceil((n1stThu-target)/604800000), 2);
                })(),
          '%w': '' + nDay,
          '%x': date.toLocaleDateString(),
          '%X': date.toLocaleTimeString(),
          '%y': ('' + nYear).slice(2),
          '%Y': nYear,
          '%z': date.toTimeString().replace(/.+GMT([+-]\d+).+/, '$1'),
          '%Z': date.toTimeString().replace(/.+\((.+?)\)$/, '$1')
        }[sMatch] || sMatch;
      });
    }

    样品使用情况:

    1
    2
    3
    4
    5
    6
    strftime('%F'); // Returns"2016-09-15"
    strftime('%A, %B %e, %Y'); // Returns"Thursday, September 15, 2016"

    // You can optionally pass it a Date object...

    strftime('%x %X', new Date('1/1/2016')); // Returns"1/1/2016 12:00:00 AM"

    这里提供了最新的代码:https://github.com/thdoan/strftime


    JSSimpleDateFormat是一个可以格式化日期对象并将格式化字符串解析回日期对象的库。它使用Java格式(SimuleDead格式化类)。月和日的名称可以本地化。

    例子:

    1
    2
    3
    var sdf = new JsSimpleDateFormat("EEEE, MMMM dd, yyyy");
    var formattedString = sdf.format(new Date());
    var dateObject = sdf.parse("Monday, June 29, 2009");

    许多框架(您可能已经在使用)具有您可能不知道的日期格式。已经提到了jqueryui,但是其他框架,如kendo-ui(全球化)、yahoo-ui(util)和angularjs也有它们。

    1
    2
    3
    4
    5
    // 11/6/2000
    kendo.toString(new Date(value),"d")

    // Monday, November 06, 2000
    kendo.toString(new Date(2000, 10, 6),"D")

    参见DTMFRM JS。如果您熟悉C的自定义日期和时间格式字符串,则此库应该执行完全相同的操作。

    演示:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    var format = new dtmFRM();
    var now = new Date().getTime();

    $('#s2').append(format.ToString(now,"This month is : MMMM") +"</br>");
    $('#s2').append(format.ToString(now,"Year is  : y or yyyy or yy") +"</br>");
    $('#s2').append(format.ToString(now,"mm/yyyy/dd") +"</br>");
    $('#s2').append(format.ToString(now,"dddd, MM yyyy") +"</br>");
    $('#s2').append(format.ToString(now,"Time is : hh:mm:ss ampm") +"</br>");
    $('#s2').append(format.ToString(now,"HH:mm") +"</br>");
    $('#s2').append(format.ToString(now,"[ddd,MMM,d,dddd]") +"</br></br>");

    now = '11/11/2011 10:15:12' ;

    $('#s2').append(format.ToString(now,"MM/dd/yyyy hh:mm:ss ampm") +"</br></br>");

    now = '40/23/2012'
    $('#s2').append(format.ToString(now,"Year is  : y or yyyy or yy") +"</br></br>");

    此问题的具体答案可在以下两行中找到:

    1
    2
    //pull the last two digits of the year
    console.log(new Date().getFullYear().toString().substr(2,2));

    格式化完整日期时间示例(mmddyy):jfiddle

    JavaScript:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
        //A function for formatting a date to MMddyy
    function formatDate(d)
    {
        //get the month
        var month = d.getMonth();
        //get the day
        var day = d.getDate();
        //get the year
        var year = d.getFullYear();
       
        //pull the last two digits of the year
        year = year.toString().substr(2,2);
       
        //increment month by 1 since it is 0 indexed
        month = month + 1;
        //converts month to a string
        month = month +"";

        //if month is 1-9 pad right with a 0 for two digits
        if (month.length == 1)
        {
            month ="0" + month;
        }

        //convert day to string
        day = day +"";

        //if day is between 1-9 pad right with a 0 for two digits
        if (day.length == 1)
        {
            day ="0" + day;
        }

        //return the string"MMddyy"
        return month + day + year;
    }

    var d = new Date();
    console.log(formatDate(d));


    1
    2
    3
    4
    5
    d = Date.now();
    d = new Date(d);
    d = (d.getMonth()+1)+'/'+d.getDate()+'/'+d.getFullYear()+' '+(d.getHours() > 12 ? d.getHours() - 12 : d.getHours())+':'+d.getMinutes()+' '+(d.getHours() >= 12 ?"PM" :"AM");

    console.log(d);


    就个人而言,因为我在相同的度量中同时使用了php和jquery/javascript,所以我使用php.js http://php js.org/functions/date中的日期函数/

    使用一个与我已知的格式字符串相同的库对我来说更容易,而且包含日期函数所有格式字符串可能性的手册当然可以在php.net上在线阅读。

    您只需使用首选方法在HTML中包含date.js文件,然后这样调用它:

    1
    2
    var d1=new Date();
    var datestring = date('Y-m-d', d1.valueOf()/1000);

    如果需要,可以使用d1.getTime()而不是valueOf(),它们执行相同的操作。

    除以1000的javascript时间戳是因为javascript时间戳以毫秒为单位,而php时间戳以秒为单位。


    虽然javascript提供了许多格式化和计算的好方法,但是我更喜欢在应用程序开发期间使用moment.js(moment js.com)库,因为它非常直观,而且节省了很多时间。

    尽管如此,我建议每个人也学习基本的JavaScriptAPI,以便更好地理解它。


    我们可以手动操作,非常直接和简单。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    var today = new Date();
           
           alert("today :"+today);
           
           var dd = today.getDate();
           alert("dd :"+dd);
           
           var mm = today.getMonth()+1; //January is 0!
           alert("mm :"+mm);
           
           var yyyy = today.getFullYear();
           
           alert("yyyy :"+yyyy);
           
           
           var hh = today.getHours();
           
           alert("hh :"+hh);
           
           var min = today.getMinutes();
           
            alert("min :"+min);
           
            var ss = today.getSeconds();
           
            alert("ss :"+ss);

           if(dd<10) {
               dd='0'+dd
           }

           if(mm<10) {
               mm='0'+mm
           }

         //  today = mm+'/'+dd+'/'+yyyy;
        // if you want / instead - then add /
         
         
         today = yyyy +"-" + mm +"-" + dd +"" + hh +":" + mm +":" + ss;
         today = yyyy +"/" + mm +"/" + dd +"" + hh +":" + mm +":" + ss;
         // use according to your choice