Skip to content

Instantly share code, notes, and snippets.

@ArtemAvramenko
Last active July 5, 2024 19:45
Show Gist options
  • Save ArtemAvramenko/d35e034cb6b410cce64d1b8944575601 to your computer and use it in GitHub Desktop.
Save ArtemAvramenko/d35e034cb6b410cce64d1b8944575601 to your computer and use it in GitHub Desktop.
Determine date and time formats in JavaScript
// https://en.wikipedia.org/wiki/Date_format_by_country
// MM/DD/YYYY USA
// DD/MM/YYYY Great Britain
// DD.MM.YYYY Germany
// DD-MM-YYYY Netherlands
// YYYY-MM-DD Canada
// YYYY/MM/DD South Africa
// YYYY.MM.DD Hungary
function getDateTimeFormats(/** @type {string | undefined} */ locale) {
let dateTime = new Date(1999, 9, 23, 18, 0, 0);
let dateText = dateTime.toLocaleDateString(locale);
const yIndex = dateText.indexOf('99');
const mIndex = dateText.indexOf('10');
const dIndex = dateText.indexOf('23');
let /** @type {string | undefined} */ separator;
if (yIndex >= 0 && mIndex >= 0 && dIndex >= 0) {
separator = dateText.match(/[\/\-\.]/)?.[0];
}
let dateFormat;
if (yIndex < mIndex || yIndex < dIndex) {
dateFormat = ['YYYY', 'MM', 'DD'].join(separator ?? '-');
} else if (mIndex < dIndex) {
dateFormat = 'MM/DD/YYYY';
} else {
dateFormat = ['DD', 'MM', 'YYYY'].join(separator ?? '/');
}
let timeFormat = 'H:mm';
if (dateTime.toLocaleTimeString(locale).indexOf('6') >= 0) {
timeFormat = 'h:mm a';
}
return { dateFormat, timeFormat }
}
let { dateFormat, timeFormat } = getDateTimeFormats();
const expect = (/** @type {any} */actual) => ({
toBe: (/** @type {any} */expected) => {
if (actual !== expected) {
console.error(actual + ' should be ' + expected)
}
}
});
console.clear();
expect(getDateTimeFormats('en-US').dateFormat).toBe('MM/DD/YYYY');
expect(getDateTimeFormats('en-GB').dateFormat).toBe('DD/MM/YYYY');
expect(getDateTimeFormats('en-CA').dateFormat).toBe('YYYY-MM-DD');
expect(getDateTimeFormats('en-ZA').dateFormat).toBe('YYYY/MM/DD');
expect(getDateTimeFormats('ja-JP').dateFormat).toBe('YYYY/MM/DD');
expect(getDateTimeFormats('de-DE').dateFormat).toBe('DD.MM.YYYY');
expect(getDateTimeFormats('cs-CZ').dateFormat).toBe('DD.MM.YYYY');
expect(getDateTimeFormats('bg-BG').dateFormat).toBe('DD.MM.YYYY');
expect(getDateTimeFormats('sr-RS').dateFormat).toBe('DD.MM.YYYY');
expect(getDateTimeFormats('lv-LV').dateFormat).toBe('DD.MM.YYYY');
expect(getDateTimeFormats('nl-NL').dateFormat).toBe('DD-MM-YYYY');
expect(getDateTimeFormats('hu-HU').dateFormat).toBe('YYYY.MM.DD');
expect(getDateTimeFormats('th-TH').dateFormat).toBe('YYYY-MM-DD');
expect(getDateTimeFormats('zh-SG').dateFormat).toBe('YYYY-MM-DD');
expect(getDateTimeFormats('en-US').timeFormat).toBe('h:mm a');
expect(getDateTimeFormats('en-GB').timeFormat).toBe('H:mm');
console.log('Tests finished');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment