0

Currently I'm getting a date as from the kendo date-picker as such (1)Sun Feb 01 2021 00:00:00 GMT+0000 (GMT). However, I would like this date to format it in dd/mm/yyyy So I did the below logic to reflect my desired date. The below implementation, returns for instance the following date 26-01/2021 but in a string type. I would like to have a Date object but not in the way stated in the above date [(1)] but something like this 26 01 2021 00:00:00 GMT.

Is this possible?


  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);
  }

4

1 回答 1

2

您可以使用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
}
于 2021-01-27T13:05:50.137 回答