Skip to content

Instantly share code, notes, and snippets.

@pangpond
Last active September 21, 2020 04:08
Show Gist options
  • Save pangpond/fb9ee8f2ec4bde3b7edc50c54dec1865 to your computer and use it in GitHub Desktop.
Save pangpond/fb9ee8f2ec4bde3b7edc50c54dec1865 to your computer and use it in GitHub Desktop.
import {default as momentNG} from 'moment';
import 'moment-timezone';
import 'moment/locale/th';
import i18n from '@src/services/i18n.service';
export const momentLocale = momentNG.locale('th');
if (momentLocale !== 'th') {
throw new Error(`Moment fell back to locale ${momentLocale}`);
}
export const toBuddhistYear = (moment, format) => {
var christianYear = moment.format('YYYY');
var buddhishYear = (parseInt(christianYear) + 543).toString();
return moment
.format(
format
.replace('YYYY', buddhishYear)
.replace('YY', buddhishYear.substring(2, 4)),
)
.replace(christianYear, buddhishYear);
};
export const toHuman = (moment, format) => {
return moment.format(format);
};
export const moment = momentNG;
export const formatJsDate = (date, format, locale) => {
const defaultDate = i18n.t('student.stats.na');
if (typeof date === 'string') {
const dateString = date.includes('.') ? date.substring(19, 0) : date;
const dateJsDate = new Date(dateString);
return dateString?.length >= 10
? localeDate(dateJsDate, format, locale)
: defaultDate;
} else {
return localeDate(date, format, locale);
}
};
const localeDate = (dateJsDate, format, locale) => {
if (locale === 'en') {
moment.locale('en');
return toHuman(moment(dateJsDate), format);
} else {
moment.locale('th');
return toBuddhistYear(moment(dateJsDate), format);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment