Get current backoffice locale in UFM filter

How can I get the current backoffice locale in a custom UFM filter?

I’m trying to add date formatting filters, using date-fns.

I think I need to consume the current user context, but I don’t think that it’s possible in a UFM filter. Am I wrong? Or is there another way of getting the current locale?

Here’s my filters by the way :slight_smile:

import { UmbUfmFilterBase } from "@umbraco-cms/backoffice/ufm";
import { formatDistance, FormatDistanceOptions } from "date-fns";

export class DateDistanceUfmFilter extends UmbUfmFilterBase {
    filter(str?: string, compareDate?: string, includeSeconds: boolean = true, addSuffix: boolean = true): string | undefined | null {
        if (!str) {
            return str;
        }

        const date1 = new Date(str);
        const date2 = compareDate ? new Date(compareDate) : new Date();

        const options: FormatDistanceOptions = {
            includeSeconds,
            addSuffix
        }

        return formatDistance(date1, date2, options)
    }
}

export { DateDistanceUfmFilter as api }
import { UmbUfmFilterBase } from "@umbraco-cms/backoffice/ufm";
import { format } from "date-fns";

export class FormatDateUfmFilter extends UmbUfmFilterBase {
    filter(str?: string, dateFormat?: string): string | undefined | null {

        if (!str || !dateFormat) {
            return str;
        }

        const date = new Date(str);
        return format(date, dateFormat);
    }
}

export { FormatDateUfmFilter as api}

I am not sure you could get a context in the filter, as looking at source code examples its simple processing once you get the value you need from the UFM Component.

So I would consider creating a custom UFM component and then the filter could be your date string format perhaps ?

The current locale is always available in the document object. You can also get it through the UmbLocalizationManager (which pulls it from the document tag anyway):

import { umbLocalizationManager } from '@umbraco-cms/backoffice/localization-api'

console.log(umbLocalizationManager.documentLanguage) // 'en-us'

Or you can do:

console.log(document.documentElement.lang) // 'en-us'
1 Like

I can recommend using the Intl API for any date and number handling. It will automatically use the browsers locale to do stuff.

We use it extensively in the UmbLocalizationController (which you can also use from any UmbLitElement) where we - among other things - have the duration function, which seems to do something similar to your DateDistance filter:

It uses the Intl.DurationFormat, which is one of the newer APIs introduced in most browsers (but still requires an as any in TypeScript :wink: )

1 Like

That’s great, thanks!

The reason for using date-fns is because I want to be able to define the format more precisely than Intl offers.

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.