如何将Date对象格式化为字符串?


当前回答

简单格式化程序:

function fmt(date, format = 'YYYY-MM-DDThh:mm:ss') {
  const pad2 = (n) => n.toString().padStart(2, '0');

  const map = {
    YYYY: date.getFullYear(),
    MM: pad2(date.getMonth() + 1),
    DD: pad2(date.getDate()),
    hh: pad2(date.getHours()),
    mm: pad2(date.getMinutes()),
    ss: pad2(date.getSeconds()),
  };

  return Object.entries(map).reduce((prev, entry) => prev.replace(...entry), format);
}

用法:

fmt(new Date(), 'YYYY-MM-DDThh:mm:ss'); // '2022-11-07T12:47:59'

其他回答

使用此步骤

const MONTHS=['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','9','Oct','Nov','Dec']const date=新日期()const dateString=`${date.getDate()}-${MONTHS[date.getMonth()]}--${date.getFullYear()}`console.log(dateString)

自定义格式设置函数:

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

函数dateToYMD(日期){var d=date.getDate();var m=date.getMonth()+1//从0到11的月份var y=date.getFullYear();返回“”+y+“-”+(m<=9?“0”+m:m)+”-“+(d<=9!“0”+d:d);}console.log(dateToYMD(新日期(2017,10,5));//11月5日

OP格式可以如下生成:

函数dateToYMD(日期){var strArray=['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];var d=date.getDate();var m=strArray[date.getMonth()];var y=date.getFullYear();返回“”+(d<=9?“0”+d:d)+“-”+“+m+”-“+y;}console.log(dateToYMD(新日期(2017,10,5));//11月5日

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

更高级的功能可以基于格式参数生成可配置的输出。

如果编写一个格式化函数太长,那么周围有很多库可以执行它。其他一些答案已经列举了它们。但日益增加的依赖性也有反作用。

标准ECMAScript格式化函数:

自从ECMAScript的最新版本以来,Date类具有一些特定的格式化函数:

toDateString:依赖于实现,仅显示日期。https://262.ecma-international.org/#sec-日期.协议类型.日期new Date().toDateString();//例如“2016年11月11日星期五”


toISOString:显示ISO 8601日期和时间。https://262.ecma-international.org/#sec-日期.协议类型.toisostringnew Date().toISOString();//例如“2016-11-21T08:00:00.000Z”


toJSON:JSON的Stringer。https://262.ecma-international.org/#sec-日期.原型.项目new Date().toJSON();//例如“2016-11-21T08:00:00.000Z”


toLocaleDateString:依赖于实现,区域设置格式的日期。https://262.ecma-international.org/#sec-日期.协议类型.颜色日期字符串new Date().toLocaleDateString();//例如“2016年11月21日”


toLocaleString:依赖于实现,是区域设置格式的日期和时间。https://262.ecma-international.org/#sec-日期.协议类型.颜色字符串new Date().toLocaleString();//例如“2016年11月21日上午08:00:00”


toLocaleTimeString:依赖于实现,以区域设置格式表示时间。https://262.ecma-international.org/#sec-日期.协议类型.颜色时间字符串new Date().toLocaleTimeString();//例如“08:00:00 AM”


toString:日期的通用toString。https://262.ecma-international.org/#sec-日期.协议类型.测试new Date().toString();//例如“2016年11月21日星期五08:00:00 GMT+0100(西欧标准时间)”

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

new Date().toISOString().slice(0,10)//返回YYYY-MM-DD

示例片段:console.log(“1)”+new Date().toDateString());console.log(“2)”+new Date().toISOString());console.log(“3)”+new Date().toJSON());console.log(“4)”+new Date().toLocaleDateString());console.log(“5)”+new Date().toLocaleString());console.log(“6)”+new Date().toLocaleTimeString());console.log(“7)”+new Date().toString());console.log(“8)”+new Date().toISOString().slice(0,10));

指定标准函数的区域设置:

上面列出的一些标准函数取决于语言环境:

到LocaleDateString()到LocaleTimeString()到LocalString()

这是因为不同的文化使用不同的格式,并以不同的方式表达他们的日期或时间。默认情况下,该函数将返回在其运行的设备上配置的格式,但这可以通过设置参数(ECMA-402)来指定。

toLocaleDateString([locales[, options]])
toLocaleTimeString([locales[, options]])
toLocaleString([locales[, options]])
//e.g. toLocaleDateString('ko-KR');

选项第二个参数允许在所选区域设置中配置更具体的格式。例如,月份可以显示为全文或删节。

toLocaleString('en-GB', { month: 'short' })
toLocaleString('en-GB', { month: 'long' })

示例片段:console.log(“1)”+new Date().toLocaleString('en-US'));console.log(“2)”+new Date().toLocaleString('ko-KR'));console.log(“3)”+新日期().toLocaleString('de-CH'));console.log(“4)”+new Date().toLocaleString('en-GB',{hour12:false}));console.log(“5)”+new Date().toLocaleString('en-GB',{hour12:true}));

关于区域设置的一些良好做法:

大多数人不喜欢他们的日期以外国人的格式显示,因此,尽可能保持默认的语言环境(而不是到处设置“en-US”)。实现从UTC到UTC的转换可能具有挑战性(考虑到DST、时区不是1小时的倍数等)。尽可能使用经过良好测试的库。不要假设语言环境与一个国家相关:几个国家都有很多语言环境(加拿大、印度等)避免通过非标准方式检测区域设置。在这里,您可以了解到多个陷阱:检测键盘布局、按地理位置检测区域设置等。。

受到JD Smith奇妙的正则表达式解决方案的启发,我突然有了一个令人震惊的想法:

var D=Date().toString().split(“”);console.log(D[2]+“-”+D[1]+“-“+D[3]);

在JavaScript中格式化DateTime的一种有用且灵活的方法是Intl.DateTimeFormat:

var date = new Date();
var options = { year: 'numeric', month: 'short', day: '2-digit'};
var _resultDate = new Intl.DateTimeFormat('en-GB', options).format(date);
// The _resultDate is: "12 Oct 2017"
// Replace all spaces with - and then log it.
console.log(_resultDate.replace(/ /g,'-'));

结果是:“2017年10月12日”

可以使用options参数自定义日期和时间格式。

Intl.DateTimeFormat对象是启用语言敏感日期和时间格式的对象的构造函数。

语法

new Intl.DateTimeFormat([locales[, options]])
Intl.DateTimeFormat.call(this[, locales[, options]])

参数

区域设置

可选择的带有BCP 47语言标记的字符串或此类字符串的数组。有关locales参数的一般形式和解释,请参阅Intl页。允许使用以下Unicode扩展密钥:

nu
Numbering system. Possible values include: "arab", "arabext", "bali", "beng", "deva", "fullwide", "gujr", "guru", "hanidec", "khmr", "knda", "laoo", "latn", "limb", "mlym", "mong", "mymr", "orya", "tamldec", "telu", "thai", "tibt".
ca
Calendar. Possible values include: "buddhist", "chinese", "coptic", "ethioaa", "ethiopic", "gregory", "hebrew", "indian", "islamic", "islamicc", "iso8601", "japanese", "persian", "roc".

选项

可选择的具有以下部分或全部财产的对象:

本地匹配器

要使用的区域设置匹配算法。可能的值是“查找”和“最佳匹配”;默认值为“最佳拟合”。有关此选项的信息,请参阅Intl页面。

时区

要使用的时区。实现必须识别的唯一值是“UTC”;默认值是运行时的默认时区。实施还可以识别IANA时区数据库的时区名称,例如“亚洲/上海”、“亚洲/加尔各答”、“美国/纽约”。

小时12

是否使用12小时(而不是24小时)。可能的值为true和false;默认值取决于区域设置。

格式匹配器

要使用的格式匹配算法。可能的值是“基本”和“最适合”;默认值为“最佳拟合”。有关使用此属性的信息,请参见以下段落。

以下财产描述了格式化输出中使用的日期时间组件及其所需的表示。需要实现至少支持以下子集:

weekday, year, month, day, hour, minute, second
weekday, year, month, day
year, month, day
year, month
month, day
hour, minute, second
hour, minute

实现可能支持其他子集,并且将针对所有可用的子集表示组合来协商请求,以找到最佳匹配。有两种算法可用于此协商,并由formatMatcher属性选择:完全指定的“基本”算法和依赖于实现的“最佳匹配”算法。

周工作日

工作日的表示。可能的值有“窄”、“短”、“长”。

era

时代的代表。可能的值有“窄”、“短”、“长”。

year

年度的表示。可能的值为“数字”、“2位数”。

月份的表示。可能的值有“数字”、“2位数”、“窄”、“短”、“长”。

day

当天的表示。可能的值为“数字”、“2位数”。

hour

小时的表示。可能的值为“数字”、“2位数”。

分钟

会议记录的表示。可能的值为“数字”、“2位数”。

第二

第二个的表示。可能的值为“数字”、“2位数”。

时区名称

时区名称的表示形式。可能的值为“短”、“长”。每个日期时间组件属性的默认值未定义,但如果所有组件财产均未定义,则假定年、月和日为“数字”。

联机检查

更多详细信息

DateFormatter.formatDate(新日期(2010,7,10),'DD-MMM-YYYY')

=>2010年8月10日

DateFormatter.formatDate(new Date(),'YYYY-MM-DD HH:MM:ss')

=>2017-11-22 19:52:37

DateFormatter.formatDate(新日期(2005,1,2,3,4,5),'D DD DDD DDD,M MM MMM MMMM,YY YYYY,h hh h hh,M MM,s ss,a a')

=>2002年2月2日星期三2005年2月5日,2003年3月3日,4月4日,5月5日上午

var日期格式设置工具={月份名称:[“一月”,“二月”,“三月”,“四月”,“五月”,“六月”,“七月”、“八月”、“九月”、“十月”、“十一月”、“十二月”],dayName:[“星期日”、“星期一”、“周二”、“周三”、“周四”、“周五”、“周六”],formatDate:函数(日期,格式){var self=this;format=self.getProperDigits(format,/d+/gi,date.getDate());format=self.getProperDigits(格式,/M+/g,date.getMonth()+1);format=format.replace(/y+/gi,函数(y){var len=y.length;var year=date.getFullYear();如果(长度==2)return(年份+“”).sslice(-2);否则如果(len==4)回归年;返回y;})format=self.getProperDigits(格式,/H+/g,date.getHours());format=self.getProperDigits(格式,/h+/g,self.getHours12(date.getHours()));format=self.getProperDigits(format,/m+/g,date.getMinutes());format=self.getProperDigits(format,/s+/gi,date.getSeconds());format=format.replace(/a/ig,函数(a){var amPm=self.getAmPm(date.getHours())如果(a==“a”)返回amPm.toUpperCase();返回amPm;})format=self.getFullOr3Letters(format,/d+/gi,self.dayNames,date.getDay())format=self.getFullOr3Letters(format,/M+/g,self.monthNames,date.getMonth())返回格式;},getProperDigits:函数(格式、正则表达式、值){return format.replace(正则表达式,函数(m){var长度=m.length;如果(长度==1)返回值;否则如果(长度==2)return(“0”+值).sslice(-2);返回m;})},getHours12:函数(小时){// https://stackoverflow.com/questions/10556879/changing-the-1-24-hour-to-1-12-hour-for-the-gethours-method返回(小时+24)%12||12;},getAmPm:函数(小时){// https://stackoverflow.com/questions/8888491/how-do-you-display-javascript-datetime-in-12-hour-am-pm-format回程时间>=12?'下午':'上午';},getFullOr3Letters:函数(格式,正则表达式,名称数组,值){return format.replace(正则表达式,函数){var len=s.length;如果(长度==3)return nameArray[value].substr(0,3);否则如果(len==4)return nameArray[value];返回s;})}}console.log(DateFormatter.formatDate(new Date(),'YYYY-MM-DD HH:MM:ss'));console.log(DateFormatter.formatDate(new Date(),'D DD DDD DDDD,M MM MMM MMMM,YY YYYY,h hh h hh,M MM,s ss,a a'));console.log(DateFormatter.formatDate(新日期(2005,1,2,3,4,5),'D DD DDD DDDD,M MM MMM MMMM,YY YYYY,h hh h hh,M MM,s ss,a a'));

格式描述取自Ionic Framework(它不支持Z、UTC时区偏移)

未彻底测试