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


当前回答

将日期格式化为不同格式

let objectDate=新日期();let day=objectDate.getDate();console.log(天);//12let currentmo=objectDate.getMonth();月=当前月+1;console.log(月+1);//1.let year=objectDate.getFullYear();console.log(年);//2023//现在您可以相应地进行设置//日/月/年console.log(日+‘/‘+月+‘/’+年);//年/月/日console.log(月+'/'+day+'/'+年);

尝试此代码-https://bbbootstrap.com/code/format-date-javascript-49065802

其他回答

不使用任何外部库的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)

嗯,我想要的是将今天的日期转换为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字符串切片外部示例

有一个新的库smarti.to.js,用于JavaScript数字、日期和JSON日期的本地化格式(Microsoft或ISO8601)。

例子:

new Date('2015-1-1').to('dd.MM.yy')         // Outputs 01.01.2015
"2015-01-01T10:11:12.123Z".to('dd.MM.yy')   // Outputs 01.01.2015

本地化文件(smarti.to.{culture}.js)中也定义了自定义的短模式。示例(smarti.to.etEE.js):

new Date('2015-1-1').to('d')                // Outputs 1.01.2015

以及多样性能力:

smarti.format('{0:n2} + {1:n2} = {2:n2}', 1, 2, 3)   // Output: 1,00 + 2,00 = 3,00

Sugar.js对Date对象有很好的扩展,包括Date.format方法。

文档中的示例:

Date.create().format('{Weekday} {Month} {dd}, {yyyy}');

Date.create().format('{12hr}:{mm}{tt}')

要获得“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。