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


当前回答

将jQuery UI插件添加到页面:

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

其他回答

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

文档中的示例:

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

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

如果您对格式的控制比当前接受的答案稍少,则可以使用Date#toLocaleDateString创建标准的特定于区域设置的渲染。区域设置和选项参数允许应用程序指定应使用其格式约定的语言,并允许对渲染进行一些自定义。

选项关键示例:

日期:当天的表示。可能的值为“数字”、“2位数”。工作日:工作日的表示。可能的值有“窄”、“短”、“长”。年份:年度的表示。可能的值为“数字”、“2位数”。月份:月份的表示。可能的值有“数字”、“2位数”、“窄”、“短”、“长”。小时:小时的表示。可能的值为“数字”、“2位数”。分钟:会议记录的表示。可能的值为“数字”、“2位数”。第二:第二个的表示。可能的值为“数字”和“2位”。

所有这些键都是可选的。您可以根据需要更改选项值的数量,这也将反映每个日期时间项的存在。

注意:如果您只想配置内容选项,但仍然使用当前区域设置,则为第一个参数传递null将导致错误。改用undefined。

对于不同的语言:

“en-US”:用于美式英语“en-GB”:用于英国英语“hi IN”:印地语“ja JP”:日语

您可以使用更多语言选项。

例如

var options={weeday:'long',year:'numeric',month:'long',day:'numeric'};var today=新日期();console.log(toLocaleDateString(“en-US”));//9/17/2016console.log(toLocaleDateString(“en-US”,选项));//2016年9月17日,星期六console.log(toLocaleDateString(“hi IN”,选项));//शनिवार, 17सितंबर 2016

您也可以使用toLocaleString()方法来实现同样的目的。唯一的区别是该函数提供了不传递任何选项的时间。

// Example
9/17/2016, 1:21:34 PM

参考文献:

toLocaleString()到LocaleDateString()

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

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

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

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

参考文献:

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

以下代码将允许您将日期格式设置为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示例。

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