angular's getLocaleDateTimeFormat function returns {1}, {0}

Viewed 617

I'm using angular's getLocaleDateTimeFormat function to display selected date-time in the input field.

getLocaleDateTimeFormat(this.injector.get(LOCALE_ID), FormatWidth.Short) function shows {1}, {0}

but when i use
getLocaleDateFormat(this.injector.get(LOCALE_ID), FormatWidth.Short) and getLocaleTimeFormat(this.injector.get(LOCALE_ID), FormatWidth.Short) each separately they display date and time properly.

Am i doing something wrong?

My function is:

` formattingDate(date: Date): string {

if (!date || typeof date == 'string') {
    return '';
}

let localeId = this.injector.get(LOCALE_ID);

let localeDateFormat = getLocaleDateFormat(localeId, FormatWidth.Short);
let localeTimeFormat = getLocaleTimeFormat(localeId, FormatWidth.Short);
let localeDateTimeFormat = getLocaleDateTimeFormat(localeId, FormatWidth.Short);
return formatDate(date, localeDateTimeFormat, localeId);

} `

the thing is getLocaleDateTimeFormat function is not getting date or time or both from date argument

2 Answers

If what you're looking for is the template e.g. "YYYY/MM/DD" then import locale data:

import localeDe from "@angular/common/locales/de";
...
localeDe[10][FormatWidth.Short]

There are four members in the array corresponding to FormatWidth enum {Short, Medium, Long, Full}

Stumbled across this when I faced the same problem. The getLocaleDateTimeFormat function doesn't appear to be designed to behave as you expect ie, it doesn't return the format string of the DateTime in the given locale, rather, it returns the order in which a DateTime is presented in that Locale, ie {Date} {Time}.

Looking at some code Here, you can see they use the getLocaleDateFormat and the getLocaleTimeFormat functions and then pass them into a formatter function that takes the result of getLocaleDateTimeFormat, the time and the date separately and spits out the expected result.

Code Example:

function getLocaleDateTime(string locale, string dateTime) {
    let fullTime = getLocaleTimeFormat(locale, FormatWidth.Medium);
    let fullDate = getLocaleDateFormat(locale, FormatWidth.Medium);
    return this.formatDateTime(getLocaleDateTimeFormat(locale, FormatWidth.Medium), [fullTime, fullDate]);
}

// Copied from https://github.com/angular/angular/blob/fe691935091aaf7090864c8111a15f7cc7e53b6c/packages/common/src/i18n/format_date.ts#L201
function formatDateTime(str, opt_values) {
    if (opt_values) {
        str = str.replace(/\{([^}]+)}/g, function (match, key) {
            return (opt_values != null && key in opt_values) ? opt_values[key] : match;
        });
    }
    return str;
}
Related