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


当前回答

如果您已经在项目中使用jQuery UI,您可以这样做:

var formatted = $.datepicker.formatDate("M d, yy", new Date("2014-07-08T09:02:21.377"));

// formatted will be 'Jul 8, 2014'

这里提供了一些可以使用的日期选择器日期格式选项。

其他回答

不使用任何外部库的JavaScript解决方案:

var now = new Date()
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
var formattedDate = now.getDate() + "-" + months[now.getMonth()] + "-" + now.getFullYear()
alert(formattedDate)

要获得“2010年8月10日”,请尝试:

var date = new Date('2010-08-10 00:00:00');
date = date.toLocaleDateString(undefined, {day:'2-digit'}) + '-' + date.toLocaleDateString(undefined, {month:'short'}) + '-' + date.toLocaleDateString(undefined, {year:'numeric'})

有关浏览器支持,请参阅toLocaleDateString。

将jQuery UI插件添加到页面:

function DateFormate(dateFormate, datetime) {
    return $.datepicker.formatDate(dateFormate, datetime);
};

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。

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