heartattack
heartattack

Reputation: 23

How to get the format YYYY-MM-DD from getLocaleDateFormat in Angular?

I have the following line of code:

getLocaleDateFormat('en-CA', FormatWidth.Long )

I want to get YYYY-MM-DD. I am getting MMMM d, y.

What do I do?

Upvotes: 1

Views: 473

Answers (2)

Zion Orent
Zion Orent

Reputation: 21

import frenchCanadianLocaleData from "@angular/common/locales/fr-CA";

Look at the return array and the 11th value in the array.

['y-MM-dd', 'd MMM y', 'd MMMM y', 'EEEE d MMMM y']

Looks like short (1st value) is correct-enough, but the rest aren't. 'y-MM-dd' shows something like 2022-12-08, which might be what you're looking for.

Time is the 12th value in the array, and it appears to be correct:

["HH 'h' mm", "HH 'h' mm 'min' ss 's'", "HH 'h' mm 'min' ss 's' z", "HH 'h' mm 'min' ss 's' zzzz"]

We needed the correct locale-specific format for date and time with seconds.

Here's what worked for us: we hard-coded the date to short, the time to medium, and just put a space between them. We ignored the data in getLocaleDateTimeFormat (13th value in the array) because what it returns wasn't helpful for us.

    const locale = 'fr-CA';
    const dateFormat = getLocaleDateFormat( locale, FormatWidth.Short );
    const timeFormat = getLocaleTimeFormat( locale, FormatWidth.Medium );
    this.dateTimeFormat = dateFormat + ' ' + timeFormat;

Upvotes: 0

Karlo Tvrdinic
Karlo Tvrdinic

Reputation: 29

From Angular 6 you can use following:

import {formatDate} from '@angular/common';
formatDate(new Date(), 'YYYY-MM-DD', 'en');

Upvotes: 0

Related Questions