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

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。

编者按:以下方法是询问者在特定浏览器上的尝试,但通常不起作用;请参阅本页上的答案以了解一些实际解决方案。

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

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()对象支持的格式说明符的文档在哪里?


当前回答

只是另一个选项,我写道:

DP_DateExtensions库

不确定它是否有用,但我发现它在几个项目中都很有用——看起来它可以满足您的需要。

支持日期/时间格式、日期数学(添加/减去日期部分)、日期比较、日期解析等。

如果你已经在使用一个框架(他们都有能力),没有理由考虑这个问题,但如果你只需要在项目中快速添加日期操作,那就给它一个机会。

其他回答

示例代码:

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

输出:

"13:45:20"

只是为了继续龚志涛的坚定回答-这处理上午/下午

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

对于好奇的人来说,有一个名为tc39/temporal的实验特性,目前正处于第3阶段,它为ECMAScript语言带来了一个现代的日期/时间API。

引用tc39网站:

日期一直是ECMAScript中的一个长期难点。这是对Temporal的建议,它是一个充当顶级命名空间(如Math)的全局对象,为ECMAScript语言带来了现代的日期/时间API。要详细了解Date的一些问题以及Temporal的动机,请参阅:Fixing JavaScript Date。

这里有一本烹饪书,可以帮助您开始学习Temporal的来龙去脉。

其他资源:

GitHub存储库-tc39/临时提案YouTube上还有一段视频,详细介绍了这一提议。本文对上述视频进行了简要概述-了解JavaScript如何使用提案时间推进DateTime如何超越时间:使用时态构建未来JavaScript应用程序

所有浏览器

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

使用new Date()创建Date对象使用.getDate()、.getMonth()和.getFullYear()分别获取日期、月份和年份根据目标格式将碎片粘贴在一起

例子:

var date='2015-11-09T10:46:15.097Z';函数格式(输入){var date=新日期(输入);返回[(“0”+date.getDate()).sslice(-2),(“0”+(date.getMonth()+1)).sslice(-2),date.getFullYear()].ejoin('/');}document.body.innerHTML=格式(日期);//产量:2015年9月11日

(另请参见此Fiddle)。


仅限现代浏览器

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

var date='2015-11-09T10:46:15.097Z';函数格式(输入){返回新日期(输入).toLocaleDateString('en-GB'{年份:'数字',月份:'2-位',天:'2位数'});}document.body.innerHTML=格式(日期);//产量:2015年9月11日

(另请参见此Fiddle)。


(*)根据MDN,“现代浏览器”是指Chrome 24+、Firefox 29+、IE11、Edge12+、Opera 15+和Safari夜间版本

如果您不需要Moment.js这样的库提供的所有功能,那么可以使用我的strftime端口。它是轻量级的(与Moment.js 2.15.0相比,减少了1.35 KB和57.9 KB),并提供了strftime()的大部分功能。

/* 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 "\n")
 * %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;
  });
}

示例用法:

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