Add createDateTimeFormat to format dates based on locale

This commit is contained in:
Winnie Hellmann 2017-12-11 13:25:49 +01:00
parent 2bad3b0eaf
commit 4f73e14f2c
4 changed files with 75 additions and 3 deletions

View file

@ -1,8 +1,7 @@
import Jed from 'jed';
import sprintf from './sprintf';
const langAttribute = document.querySelector('html').getAttribute('lang');
const lang = (langAttribute || 'en').replace(/-/g, '_');
const languageCode = () => document.querySelector('html').getAttribute('lang') || 'en';
const locale = new Jed(window.translations || {});
delete window.translations;
@ -47,9 +46,19 @@ const pgettext = (keyOrContext, key) => {
return translated[translated.length - 1];
};
export { lang };
/**
Creates an instance of Intl.DateTimeFormat for the current locale.
@param formatOptions for available options, please see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat
@returns {Intl.DateTimeFormat}
*/
const createDateTimeFormat =
formatOptions => Intl.DateTimeFormat(languageCode(), formatOptions);
export { languageCode };
export { gettext as __ };
export { ngettext as n__ };
export { pgettext as s__ };
export { sprintf };
export { createDateTimeFormat };
export default locale;

View file

@ -0,0 +1,5 @@
---
title: Translate date ranges on contributors page
merge_request: 15846
author:
type: changed

View file

@ -262,6 +262,21 @@ Sometimes you need to add some context to the text that you want to translate
s__('OpenedNDaysAgo|Opened')
```
### Dates / times
- In JavaScript:
```js
import { createDateTimeFormat } from '.../locale';
const dateFormat = createDateTimeFormat({ year: 'numeric', month: 'long', day: 'numeric' });
console.log(dateFormat.format(new Date('2063-04-05'))) // April 5, 2063
```
This makes use of [`Intl.DateTimeFormat`].
[`Intl.DateTimeFormat`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat
## Adding a new language
Let's suppose you want to add translations for a new language, let's say French.

View file

@ -0,0 +1,43 @@
import { createDateTimeFormat, languageCode } from '~/locale';
const setLanguage = (languageCode) => {
const htmlElement = document.querySelector('html');
if (languageCode) {
htmlElement.setAttribute('lang', languageCode);
} else {
htmlElement.removeAttribute('lang');
}
};
describe('locale', () => {
afterEach(() => {
setLanguage(null);
});
describe('languageCode', () => {
it('parses the lang attribute', () => {
setLanguage('ja');
expect(languageCode()).toBe('ja');
});
it('falls back to English', () => {
setLanguage(null);
expect(languageCode()).toBe('en');
});
});
describe('createDateTimeFormat', () => {
beforeEach(() => {
setLanguage('de');
});
it('creates an instance of Intl.DateTimeFormat', () => {
const dateFormat = createDateTimeFormat({ year: 'numeric', month: 'long', day: 'numeric' });
expect(dateFormat.format(new Date(2015, 6, 3))).toBe('3. Juli 2015');
});
});
});