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


当前回答

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

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

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

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

参考文献:

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

其他回答

只需执行以下操作:-


 let date = new Date().toLocaleDateString('en-us',{day: 'numeric'})
 let month = new Date().toLocaleDateString('en-us',{month: 'long'})
 let year = new Date().toLocaleDateString('en-us',{year: 'numeric'})
 const FormattedDate = `${date}-${month}-${year}`
 console.log(FormattedDate) // 26-March-2022

这是修改为3个字符月和2位数年的主要答案:

函数formatDate(日期){var monthNames=[“一月”,“二月”,“三月”,“四月”,“五月”,“六月”,“七月”,“八月”,“九月”,“十月”,“十一月”,“十二月”];var day=date.getDate(),monthIndex=date.getMonth(),year=date.getFullYear().toString().substr(-2);return day+''+monthNames[monthIndex]+''+年;}document.write(formatDate(newDate()));

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

以下代码将允许您将日期格式设置为DD-MM-YYYY(2017年12月27日)或DD-MM-YYYY(2017年10月26日):

/** Pad number to fit into nearest power of 10 */
function padNumber(number, prependChar, count) {
  var out = '' + number; var i;
  if (number < Math.pow(10, count))
    while (out.length < ('' + Math.pow(10, count)).length) out = prependChar + out;
  
  return out;
}

/* Format the date to 'DD-MM-YYYY' or 'DD MMM YYYY' */
function dateToDMY(date, useNumbersOnly) {
  var months = [
    'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 
    'Nov', 'Dec'
  ];

  return '' + padNumber(date.getDate(), '0', 1) + 
   (useNumbersOnly? '-' + padNumber(date.getMonth() + 1, '0', 1) + '-' : ' ' + months[date.getMonth()] + ' ')
    + date.getFullYear();
}

更改date.getFullYear()和padNumber(date.getDate(),“0”,1)的顺序,以生成dateToYMD()函数。

有关详细信息,请参见repl.it示例。

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