Is there a way to format a Javascript data into dd-mm-yyyy?

1.3k views Asked by At

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

1

There are 1 answers

1
Kul On

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
}