在JavaScript中,如何将日期对象格式化为10-Aug-2010

推荐答案

对于自定义分隔的日期格式,必须拉出日期(或时间)

要做到这一点,您可以使用DateTimeFormat#formatToParts.你可以 构造数组,但这并不理想,因为数组输出取决于 区域设置:

{ // example 1
   let f = new Intl.DateTimeFormat('en');
   let a = f.formatToParts();
   console.log(a);
}
{ // example 2
   let f = new Intl.DateTimeFormat('hi');
   let a = f.formatToParts();
   console.log(a);
}

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

function join(t, a, s) {
   function format(m) {
      let f = new Intl.DateTimeFormat('en', m);
      return f.format(t);
   }
   return a.map(format).join(s);
}

let a = [{day: 'numeric'}, {month: 'short'}, {year: 'numeric'}];
let s = join(new Date, a, '-');
console.log(s);

您还可以使用以下命令逐个取出DateTimeFormat的部件 DateTimeFormat#format,但请注意,使用此方法时,截至3月 2020年,ECMAScript实现中有a bug个 分钟和秒的前导零(该方法绕过了此错误 (上图).

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

当处理日期和时间时,通常值得使用库(例如.

请注意,在上述解决方案中使用的ECMAScript国际化API

Javascript相关问答推荐

如何通过onClick为一组按钮分配功能;

有Angular 的material .未应用收件箱中的价值变化

如何才能拥有在jQuery终端中执行命令的链接?

判断表格单元格中是否存在文本框

如何使用JavaScript将文本插入空div

Chromium会将URL与JS一起传递到V8吗?

无法读取未定义错误的属性路径名''

我的角模板订阅后不刷新'

在open shadow—root中匹配时,使用jQuery删除一个封闭的div类

Phaserjs-创建带有层纹理的精灵层以自定义外观

在表单集中保存更改时删除';禁用';

使用jQuery find()获取元素的属性

如何使用Astro优化大图像?

如何组合Multer上传?

Node.js错误: node 不可单击或不是元素

MongoDB中的嵌套搜索

构建器模式与参数对象输入

无法在Adyen自定义卡安全字段创建中使用自定义占位符

在HTML中使用meta标记来指定定制元数据以用于使用JavaScript进行检索是不是一个坏主意?

如果未定义,如何添加全局变量