Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Auto translate date format based on current i18n Locale #673

Merged
merged 2 commits into from
Jun 21, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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