Reputation: 14863
How can we get the format used, when a date is formatted as a shortDate
(or any other formatting). Background: Depending on the local, a the 'shortDate' formats dates differently.
Example:
Since our user can switch languages, it is not obvious which format is used. Which then can be quite confusing. To help him we want to display the used date-format, but I cannot find a way to get it.
Stackblitz sample: https://stackblitz.com/edit/angular-ivy-kyjabd?file=src%2Fapp%2Fapp.component.html
What we have tried:
We looked, how the formatDate
gets the format information, however the getNamedFormat
function is not exported.
Samplecode
import { Component } from '@angular/core';
import { formatDate } from '@angular/common';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
deDate;
enDate;
enGbDate;
constructor() {
const date = Date.now();
this.deDate = formatDate(date, 'shortDate', 'de');
this.enDate = formatDate(date, 'shortDate', 'en');
this.enGbDate = formatDate(date, 'shortDate', 'en-GB');
}
}
Upvotes: 0
Views: 1712
Reputation: 3727
You can use getLocaleDateFormat
from angular/common package:
import { FormatWidth, getLocaleDateFormat } from '@angular/common';
then
getLocaleDateFormat(locale, FormatWidth.Short)
Where locale is string value such as en-US etc.
LocaleDateFormat returned is correct and based on this Angular is formatting the date. If you are looking for exact format, you might need to create a map of short date format as per locale and get it from there:
getLocaleDateString(locale): string {
// All you locale short format goes here
const formats = {
"de": "DD.MM.YYYY",
"en-GB": "DD/MM/YYYY",
};
return formats[locale] || "dd/MM/yyyy";
}
Check this: https://stackblitz.com/edit/angular-ivy-cuu2jo?file=src%2Fapp%2Fapp.component.ts
Upvotes: 3