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


当前回答

好的,我们有一个叫做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文档。

其他回答

嗯,我想要的是将今天的日期转换为MySQL友好的日期字符串,如2012-06-23,并在我的一个查询中使用该字符串作为参数。我找到的简单解决方案是:

var today = new Date().toISOString().slice(0, 10);

请记住,上述解决方案没有考虑您的时区偏移。

您可以考虑改用此函数:

function toJSONLocal (date) {
    var local = new Date(date);
    local.setMinutes(date.getMinutes() - date.getTimezoneOffset());
    return local.toJSON().slice(0, 10);
}

这将为您提供正确的日期,以防您在一天的开始/结束时执行此代码。

var date=新日期();函数到本地(日期){var local=新日期(日期);local.setMinutes(date.getMinutes()-date.getTimezoneOffset());return local.toJSON();}函数到JSONLocal(日期){var local=新日期(日期);local.setMinutes(date.getMinutes()-date.getTimezoneOffset());return local.toJSON().slice(0,10);}//查看您的devtools控制台console.log(date.toJSON());console.log(date.toISOString());console.log(toLocal(日期));console.log(toJSONLocal(日期));

日期.toISOString日期.toJSON字符串切片外部示例

Date构造函数(和Date.parse())在构造日期时只接受一种格式作为参数,即ISO 8601:

// new Date('YYYY-MM-DDTHH:mm:ss.sssZ')
const date = new Date('2017-08-15')

但由于浏览器的差异和不一致性,强烈不建议从字符串中解析(MDN建议不要使用日期字符串创建日期)。

建议的替代方法是直接从数字数据构建Date实例,如下所示:

new Date(2017, 7, 15) // Month is zero-indexed

这就是解析。现在,要将日期格式化为所需的字符串,您有几个date对象的本地选项(尽管我认为没有一个符合您所需的格式):

date.toString()       // 'Wed Jan 23 2019 17:23:42 GMT+0800 (Singapore Standard Time)'
date.toDateString()   // 'Wed Jan 23 2019'
date.toLocaleString() // '23/01/2019, 17:23:42'
date.toGMTString()    // 'Wed, 23 Jan 2019 09:23:42 GMT'
date.toUTCString()    // 'Wed, 23 Jan 2019 09:23:42 GMT'
date.toISOString()    // '2019-01-23T09:23:42.079Z'

对于其他格式选项,恐怕您必须使用Moment.js、day.js等库。

这篇文章中的日期格式提示归功于Zell Liew。

如果在代码中使用jQueryUI,则有一个内置函数,名为formatDate()。我用这种方式设置今天的日期:

var testdate = Date();
testdate = $.datepicker.formatDate( "d-M-yy",new Date(testdate));
alert(testdate);

在jQueryUI文档中可以看到许多其他格式化日期的示例。

试试看:

函数init(){var d=新日期();var day=d.getDate();var x=d.toDateString().substr(4,3);var year=d.getFullYear();document.querySelector(“#mydate”).innerHTML=day+'-'+x+'-'+年;}window.onload=init;<div id=“mydate”></div>

@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"