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


当前回答

它在InternetExplorer11、Firefox和Chrome中的工作方式相同(当选择en-UK时,Chrome80.x显示12小时格式)。

const d=新日期('2010/08/05 23:45')//26.3.2020const dtfUK=新Intl.DateTimeFormat('UK',{年:'数字',月:'2位数',日:'2位',小时:'2-位数',分钟:'2-位',秒:'2-数位'})//const dtfUS=新Intl.DateTimeFormat('en',{年:'数字',月:'2位数',日:'2位',小时:'2-位数',分钟:'2-位',秒:'2-数位'})//console.log(dtfUS.format(d));//2010年5月8日下午11:45:00console.log(dtfUK.format(d));//05.08.2010 23:45:00/*node.js:2010年5月8日,晚上11:45:002010-08-05 23:45:00*/

有什么更一般的吗?

var d=新日期('2010-08-10T10:34:56.789Z');var str=d.toDateString()+/-2010年8月10日星期二“”+d.toTimeString().split(“”)[0]+/-12:34:56,GMT+0x0(GMT+00:00)“”+(d.getMonth()+101)+/-108“”+d.获取毫秒();//789console.log(str);//2010年8月10日星期二12:34:56 108 789console.log(//$1周二$2 8月$3 11$4 2020$5 12$6 34$7 56$8 108$9 789str.replace(/(\S{3})(\S}3)(\d{1,2})); // 2010年8月10日12:34.789(星期二)/*$1:星期二工作日字符串$2:8月短文本$3:11天$4:2010年$5:12小时$6:34分钟$7:56秒$8:08个月$9:789毫秒*/

或例如1行IIFE“库”;-)

控制台日志((函数(frm,d){return[d.toDateString(),d.toTimeString().split(“”)[0],(d.getMonth()+101),d.getMilliseconds()].jjoin(“).replace(/(\S{3})(\S})('$4/$8/$3$5:$6($1)',新日期()));

如果不需要,可以删除无用的部件和/或更改索引。

其他回答

在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位数”。

时区名称

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

联机检查

更多详细信息

我们有很多解决方案,但我认为最好的是Moment.js。所以我个人建议将Moment.jss用于日期和时间操作。

console.log(moment().format('DD-MMM-YYYY'));<script src=“//cdnjs.cloudflare.com/ajax/libs/ment.js/2.14.1/moment.min.js”></script>

一行中请求的格式-没有库和Date方法,只有正则表达式:

var d = (new Date()).toString().replace(/\S+\s(\S+)\s(\d+)\s(\d+)\s.*/,'$2-$1-$3');
// date will be formatted as "14-Oct-2015" (pass any date object in place of 'new Date()')

在我的测试中,这在主要浏览器(Chrome、Safari、Firefox和IE)中可靠地工作。正如@RobG所指出的,Date.protype.toString()的输出依赖于实现,因此对于国际或非浏览器实现,只需测试输出,以确保它在JavaScript引擎中正常工作。您甚至可以添加一些代码来测试字符串输出,并在执行正则表达式替换之前确保其与预期匹配。

好的,我们有一个叫做Intl的东西,这对在JavaScript中格式化日期非常有用:

您的日期如下:

var date = '10/8/2010';

然后使用如下所示的新Date()更改为Date:

date = new Date(date);

现在,您可以使用以下区域设置列表以任何方式对其进行格式化:

date = new Intl.DateTimeFormat('en-AU').format(date); // Australian date format: "8/10/2010" 

date = new Intl.DateTimeFormat('en-US').format(date); // USA date format: "10/8/2010" 

date = new Intl.DateTimeFormat('ar-EG').format(date);  // Arabic date format: "٨‏/١٠‏/٢٠١٠"

如果您确实想要上面提到的格式,可以执行以下操作:

date = new Date(Date.UTC(2010, 7, 10, 0, 0, 0));
var options = {year: "numeric", month: "short", day: "numeric"};
date = new Intl.DateTimeFormat("en-AU", options).format(date).replace(/\s/g, '-');

结果将是:

"10-Aug-2010"

有关详细信息,请参阅Intl API和Intl.DateTimeFormat文档。

@Sébastien——可选的所有浏览器支持

new Date(parseInt(496407600)*1000).toLocaleDateString('de-DE', {
year: 'numeric',
month: '2-digit',
day: '2-digit'
}).replace(/\./g, '/');

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


基于Date.toLocaleDateString的高阶标记模板文本示例:

const date = new Date(Date.UTC(2020, 4, 2, 3, 23, 16, 738));
const fmt = (dt, lc = "en-US") => (str, ...expr) =>
    str.map((str, i) => str + (expr[i]?dt.toLocaleDateString(lc, expr[i]) :'')).join('')

console.log(fmt(date)`${{year: 'numeric'}}-${{month: '2-digit'}}-${{day: '2-digit'}}`);
// expected output: "2020-05-02"