Skip to content

Commit

Permalink
Add new localeFormat API for locale-based formatting (using Intl API)
Browse files Browse the repository at this point in the history
  • Loading branch information
Antoni Kepinski committed Aug 24, 2020
1 parent 3c8aaac commit da943ae
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
29 changes: 29 additions & 0 deletions src/locale.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/**
* Use this API for locale-based formatting.
* @param {Date} date - Date object, which should be used.
* @param {string} exp - String, which you want to format, for example: {yyyy}-{MM}-{dd} or Current time: {hh}:{mm}:{ss}.
* @param {string | string[] = 'en-US'} locale - Locale(s), which will be used for formatting.
* @return {string} String with formatted date.
*/
export default (date: Date, exp: string, locale: string | string[] = 'en-US'): string => exp.replace(/{.*?}/g, key => {
const shortWeekday = new Intl.DateTimeFormat(locale, {weekday: 'short'}).format(date);
switch (key) {
case '{MMMMM}':
return new Intl.DateTimeFormat(locale, {month: 'narrow'}).format(date);
case '{MMMM}':
return new Intl.DateTimeFormat(locale, {month: 'long'}).format(date);
case '{MMM}':
return new Intl.DateTimeFormat(locale, {month: 'short'}).format(date);
case '{EEEEE}':
return new Intl.DateTimeFormat(locale, {weekday: 'narrow'}).format(date);
case '{EEEE}':
return new Intl.DateTimeFormat(locale, {weekday: 'long'}).format(date);
case '{EEE}':
case '{EE}':
case '{E}':
return shortWeekday;
/* c8 ignore next 2 */
default:
return '';
}
});
17 changes: 17 additions & 0 deletions test/locale.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import test from 'ava';
import {localeFormat} from '../src';

const foo = new Date('8/1/2020, 4:30:09 PM');

test('general', t => {
t.is(localeFormat(foo, 'foo'), 'foo', 'does nothing if no match');
t.is(localeFormat(foo, 'MMM'), 'MMM', 'does nothing if no `{}` wrappers');
t.is(localeFormat(foo, '{MMM}'), 'Aug', 'returns abbreviated month');
t.is(localeFormat(foo, '{MMMM}'), 'August', 'returns wide month');
t.is(localeFormat(foo, '{MMMMM}'), 'A', 'returns narrow month');
t.is(localeFormat(foo, '{E}'), 'Sat', 'returns abbreviated day of week');
t.is(localeFormat(foo, '{EE}'), 'Sat', 'returns abbreviated day of week');
t.is(localeFormat(foo, '{EEE}'), 'Sat', 'returns abbreviated day of week');
t.is(localeFormat(foo, '{EEEE}'), 'Saturday', 'returns wide day of week');
t.is(localeFormat(foo, '{EEEEE}'), 'S', 'returns narrow day of week');
});

0 comments on commit da943ae

Please # to comment.