【问题标题】:Is there a way to format a Javascript data into dd-mm-yyyy? [duplicate]有没有办法将 Javascript 数据格式化为 dd-mm-yyyy? [复制]
【发布时间】:2021-05-01 07:30:56
【问题描述】:

目前我正在从剑道日期选择器中获取日期,例如 (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);
  }

【问题讨论】:

标签: javascript typescript datetime datetime-format kendo-datetimepicker


【解决方案1】:

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

问题提到了dd-mm-yyyy 和dd/mm/yyyy 格式,所以这里有两个可以帮助的sn-ps:

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
}

【讨论】:

猜你喜欢
  • 2013-03-18
  • 1970-01-01
  • 2018-09-01
  • 2015-11-03
  • 1970-01-01
  • 1970-01-01
  • 2018-04-02
  • 2016-12-13
  • 2017-03-08
相关资源
最近更新 更多