How to return custom date format with localization in TypeScript / JavaScript
Obviously, true developers prefer to return the date in a digital format, for example, '24.01.2024', '24-01-2024' and various combinations of this. But customers often want to work with human dates. In this post you can find how to return the custom localized date and how to use it with a Fluent-UI component DatePicker.
When I work with TypeScript / JavaScript and I use variables of the Date type, I prefer not to invent a bicycle and use 'momentjs' instead. You can add it to your React application with a line like this:
import * as moment from 'moment';
As I often make applications for SharePoint, so I use Microsoft components from FluentUI (office ui fabric in previous versions). They look like Microsoft components out-of-box and they are usually can be easily built in SharePoint interfaces.
For one project I had to work with the date in German format. The required format for the date was 'Wochetag, Day.Month.Year'. It should look like this: 'Mittwoch, 24.01.2024'. And this format must be used regardless to user settings.
That's how I made it work
<DatePicker className={styles.datepicker} strings={this.getDatePickerStrings()}
allowTextInput value={this.state.timeBis}
formatDate={ (date?: Date): string => {
return !date ? '' : moment(date).locale('de-DE').format('dddd, DD.MM.YYYY')
}}
onSelectDate={(e) => this.changeBis(e)}
/>
The 'strings' is a IDatePickerStrings object and it is returned by a method:
public getDatePickerStrings(): IDatePickerStrings {
const localeData: moment.Locale = moment.localeData('de-DE');
return {
months: localeData.months(),
shortMonths: localeData.monthsShort(),
days: localeData.weekdays(),
shortDays: localeData.weekdaysMin(),
goToToday: 'Heute',
prevMonthAriaLabel: 'vorheriger Monat',
nextMonthAriaLabel: 'nächster Monat',
prevYearAriaLabel: 'vorheriges Jahr',
nextYearAriaLabel: 'nächstes Jahr'
};
}
Probably, it can be not the most attractive solution, but it 100% works good.
You can find more documentation about date format for MomentJs at the Docs page Moment.js | Docs (momentjs.com)