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


当前回答

简单格式化程序:

function fmt(date, format = 'YYYY-MM-DDThh:mm:ss') {
  const pad2 = (n) => n.toString().padStart(2, '0');

  const map = {
    YYYY: date.getFullYear(),
    MM: pad2(date.getMonth() + 1),
    DD: pad2(date.getDate()),
    hh: pad2(date.getHours()),
    mm: pad2(date.getMinutes()),
    ss: pad2(date.getSeconds()),
  };

  return Object.entries(map).reduce((prev, entry) => prev.replace(...entry), format);
}

用法:

fmt(new Date(), 'YYYY-MM-DDThh:mm:ss'); // '2022-11-07T12:47:59'

其他回答

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

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

// formatted will be 'Jul 8, 2014'

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

大家好,我有一个代码,用于为日期添加日期和格式。

 const FechaMaxima = new Date();
 FechaMaxima.setDate(FechaMaxima.getDate() + 6);
 FechaMaxima.toISOString().substring(0, 10);

对于自定义分隔日期格式,必须拉出日期(或时间)DateTimeFormat对象(它是ECMAScript国际化API),然后手动创建字符串使用所需的分隔符。

为此,可以使用DateTimeFormat#formatToParts。你可以销毁数组,但这并不理想,因为数组输出取决于区域设置:

{//示例1设f=新Intl.DateTimeFormat('en');让a=f.formatToParts();控制台日志(a);}{//示例2设f=新Intl.DateTimeFormat('hi');让a=f.formatToParts();控制台日志(a);}

最好将格式数组映射到结果字符串:

函数连接(t,a,s){函数格式(m){设f=新Intl.DateTimeFormat('en',m);返回f.format(t);}返回.map(格式).join(s);}让a=〔{日:‘数字’},{月:‘短’}、{年:‘数字”}〕;let s=join(新日期,a,'-');console.log;

还可以使用DateTimeFormat#格式,但请注意,使用此方法时,截至3月2020年,当涉及到分钟和秒的前导零(该方法避免了此错误以上)。

设d=新日期(2010,7,5);let ye=新Intl.DateTimeFormat('en',{year:'numeric'}).format(d);let mo=新Intl.DateTimeFormat('en',{month:'short'}).format(d);let da=新Intl.DateTimeFormat('en',{day:'2-位'}).format(d);console.log(`${da}--${mo}-${ye}');

在处理日期和时间时,通常值得使用库(例如,luxon、date fns、moment.js不建议用于新项目),因为该领域有许多隐藏的复杂性。

注意,上述解决方案中使用的ECMAScript国际化APIIE10不支持(2月全球浏览器市场份额为0.03%)2020).

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

受到JD Smith奇妙的正则表达式解决方案的启发,我突然有了一个令人震惊的想法:

var D=Date().toString().split(“”);console.log(D[2]+“-”+D[1]+“-“+D[3]);