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


当前回答

在我的情况下,我已将日期表“2022年7月1日”格式化为“2022-07-01”

常量格式日期=日期=>{const d=新日期(日期)let month=(d.getMonth()+1).toString()let day=d.getDate().toString()const year=d.getFullYear()如果(月长度<2){月=“0”+月}如果(日长度<2){天=“0”+天}return[年,月,日]。join('-')}console.log(格式日期('01/07/2022'))

其他回答

new Date().toLocaleDateString()// "3/21/2018"

developer.mozilla.org上的更多文档

使用ECMAScript Edition 6(ES6/ES2015)字符串模板:

let d = new Date();
let formatted = `${d.getFullYear()}-${d.getMonth() + 1}-${d.getDate()}`;

如果需要更改分隔符:

const delimiter = '/';
let formatted = [d.getFullYear(), d.getMonth() + 1, d.getDate()].join(delimiter);

注意(2022-10):toLocaleFormat已被弃用一段时间,并从Firefox版本58中删除。请参见LocaleFormat

我想你可以使用非标准的Date方法来LocaleFormat(formatString)

formatString:与C中strftime()函数期望的格式相同的格式字符串。

var today = new Date();
today.toLocaleFormat('%d-%b-%Y'); // 30-Dec-2011

参考文献:

到区域设置格式斯特夫蒂姆

一行中请求的格式-没有库和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引擎中正常工作。您甚至可以添加一些代码来测试字符串输出,并在执行正则表达式替换之前确保其与预期匹配。

var today = new Date();
var formattedToday = today.toLocaleDateString() + ' ' + today.toLocaleTimeString();