1

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

Csibi Norbert
  • 780
  • 1
  • 11
  • 35
  • 1
    Does this answer your question? [Format Date() in JS](https://stackoverflow.com/questions/45880161/format-date-in-js) – evolutionxbox Jan 27 '21 at 12:54

1 Answers1

2

You can use Intl.DateTimeFormat for formatting date as per a particular locale.

The question mentions both dd-mm-yyyy and dd/mm/yyyy formats so here are two snippets that would help:

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
}
Kul
  • 1,239
  • 8
  • 18
  • Note that the results of [*Intl.DateTimeFormat#format*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/format) are implementation dependent and may not return the result you expect. – RobG Jan 27 '21 at 22:28