有没有办法将 Javascript 数据格式化为 dd-mm-yyyy?

问题描述

目前我正在从剑道日期选择器中获取日期 (1)Sun Feb 01 2021 00:00:00 GMT+0000 (GMT)。但是,我希望将此日期格式化为 dd/mm/yyyy 所以我做了以下逻辑来反映我想要的日期。下面的实现,例如返回以下日期 26-01/2021,但采用字符串类型。我想要一个 Date 对象,但不是上述日期 [(1)] 中所述的方式,而是类似于 26 01 2021 00:00:00 GMT

这可能吗?


  public static formatDate(dt: Date): string {
    const isValid = this.isValidDate(dt);
    if (isValid) {
      const formattedDate = dt.toLocaleDateString('en-GB',{
      day: 'numeric',month: 'numeric',year: 'numeric'
      }).replace(/\//g,'-');
      return formattedDate;
    }
    return null;
  }

  public static isValidDate(date) {
    return date && Object.prototype.toString.call(date) === "[object Date]" && !isNaN(date);
  }

解决方法

您可以使用 Intl.DateTimeFormat 根据特定区域设置格式化日期。

这个问题同时提到了 dd-mm-yyyydd/mm/yyyy 格式,所以这里有两个片段会有所帮助:

public static formatDate(dt: Date): string {
  return new Intl.DateTimeFormat('en-GB').format(dt); // returns the date in dd/mm/yyyy format
}
public static formatDate(dt: Date): string {
  return new Intl.DateTimeFormat('en-GB').format(dt).replace(/\//g,'-'); // returns the date in dd-mm-yyyy format
}