Skip to content

Commit

Permalink
Merge pull request #673 from bcgov/localize-formatted-dates-tenant-ui
Browse files Browse the repository at this point in the history
Auto translate date format based on current i18n Locale
  • Loading branch information
loneil committed Jun 21, 2023
2 parents fa95192 + e7cbb7e commit 6f5cb57
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,11 @@
<script setup lang="ts">
import Dropdown from 'primevue/dropdown';
import { useI18n } from 'vue-i18n';
import { I18nLocale } from '@/helpers';
const { locale } = useI18n({ useScope: 'global' });
const localeList = ['en', 'fr', 'jp'];
const localeList: Array<I18nLocale> = ['en', 'fr', 'jp'];
</script>

<style lang="scss" scoped>
Expand Down
33 changes: 32 additions & 1 deletion services/tenant-ui/frontend/src/helpers/index.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,41 @@
import { format, fromUnixTime, parseJSON } from 'date-fns';
import { enCA, fr, ja } from 'date-fns/locale';
import { useI18n } from 'vue-i18n';

export type I18nLocale = 'en' | 'fr' | 'jp';

function i18n2DateLocale(i18nLocale: I18nLocale): Locale {
switch (i18nLocale) {
case 'en':
return enCA;
case 'fr':
return fr;
case 'jp':
return ja;
}
// This way we can fall back to a default while using typescript to
// enforce that all instances of i18nLocale have a corresponding case in the
// switch statement
/* eslint no-unreachable: "error" */
throw new Error('No valid date-fn');
}

function _dateFnsFormat(value: string, formatter: string) {
const { locale } = useI18n();
const formatted = '';
try {
if (value) {
return format(parseJSON(value), formatter);
try {
return format(parseJSON(value), formatter, {
locale: i18n2DateLocale(locale.value as I18nLocale),
});
} catch {
// Incase the locale was never set (used outside of a vue component)
console.log(
`No valid translation found for ${locale.value} defaulting to enCA`
);
return format(parseJSON(value), formatter, { locale: enCA });
}
}
} catch (error) {
console.error(`_dateFnsFormat: Error parsing ${value} to ${error}`);
Expand Down

0 comments on commit 6f5cb57

Please sign in to comment.