如何将Date对象格式化为字符串?
当前回答
大家好,我有一个代码,用于为日期添加日期和格式。
const FechaMaxima = new Date();
FechaMaxima.setDate(FechaMaxima.getDate() + 6);
FechaMaxima.toISOString().substring(0, 10);
其他回答
该模块可以轻松处理几乎所有的情况。它是一个更大的npm包的一部分,由Locutus提供,该包包含多种功能,但它可以完全独立于包本身使用,如果不使用npm(从模块更改为仅功能),只需复制粘贴/调整一点即可。
作为第二个参数,它接受时间戳,它可以来自任何地方,例如Date.getTime()。
此外,Locutus还在locatus包中维护了一个更大的datetime模块,这将提供一种更面向对象的使用方法。
在这里,您可以看到其他日期时间函数(作为模块),这些函数也非常有用。
您可以在这里找到关于参数和格式字符串的文档(注意,文档站点是一个PHP站点,但locatus实现遵循完全相同的规范)。
日期模块示例
date('H:m:s \\m \\i\\s \\m\\o\\n\\t\\h', 1062402400)//'07:09:40 m is month'
date('F j, Y, g:i a', 1062462400)//'September 2, 2003, 12:26 am'
date('Y W o', 1062462400)//'2003 36 2003'
var $x = date('Y m d', (new Date()).getTime() / 1000) $x = $x + '' var $result = $x.length // 2009 01 09 10
date('W', 1104534000) //'52'
date('B t', 1104534000) //'999 31'
date('W U', 1293750000.82); // 2010-12-31 '52 1293750000'
date('W', 1293836400); // 2011-01-01 '52'
date('W Y-m-d', 1293974054); // 2011-01-02 '52 2011-01-02'
Sugar.js对Date对象有很好的扩展,包括Date.format方法。
文档中的示例:
Date.create().format('{Weekday} {Month} {dd}, {yyyy}');
Date.create().format('{12hr}:{mm}{tt}')
受到JD Smith奇妙的正则表达式解决方案的启发,我突然有了一个令人震惊的想法:
var D=Date().toString().split(“”);console.log(D[2]+“-”+D[1]+“-“+D[3]);
注意(2022-10):toLocaleFormat已被弃用一段时间,并从Firefox版本58中删除。请参见LocaleFormat
我想你可以使用非标准的Date方法来LocaleFormat(formatString)
formatString:与C中strftime()函数期望的格式相同的格式字符串。
var today = new Date();
today.toLocaleFormat('%d-%b-%Y'); // 30-Dec-2011
参考文献:
到区域设置格式斯特夫蒂姆
在现代浏览器(*)中,您可以这样做:
var today = new Date().toLocaleDateString('en-GB', {
day : 'numeric',
month : 'short',
year : 'numeric'
}).split(' ').join('-');
如果今天(1月24日)执行输出ᵗʰ, 2016):
'24-Jan-2016'
(*)根据MDN,“现代浏览器”是指Chrome 24+、Firefox 29+、Internet Explorer 11、Edge 12+、Opera 15+和Safari夜间版本。