import { format, parse } from 'date-fns'; import locale from "date-fns/locale/fr"; export default class DatesUtils { private $dateFns: dateFns; private $t: any private $i18n: any private ISO_FORMAT = 'yyyy-MM-dd'; constructor(dateFns: dateFns, t: any, i18n: any) { this.$dateFns = dateFns this.$t = t this.$i18n = i18n } formatIso(date: Date): string { return format(date, this.ISO_FORMAT) } today(): Date { return new Date() } todayIso(): string { return this.formatIso(this.today()) } formatIsoDate(date: string, fmt: string): string { return format(parse(date, this.ISO_FORMAT, new Date()), fmt); } reformatDate(date: string, fromFormat: string, toFormat: string): string { return format(parse(date, fromFormat, new Date()), toFormat); } formatDate(date: Date, short = true): string { return short ? this.$dateFns.format(date, 'dd/MM/yyyy') : this.$dateFns.format(date, 'dd MMM yyyy', {locale: locale}) } formatTime(date: Date): string { return this.$dateFns.format(date, "HH'h'mm") } formatDateTime(date: Date): string { return this.formatDate(date) + ' ' + this.$t('on_hour') + ' ' + this.formatTime(date) } formatDateIntervalFor(dateStart: Date | null = null, dateEnd: Date | null = null): string { if (dateStart === null && dateEnd !== null) { return this.formatDateTime(dateEnd) } else if (dateEnd === null && dateStart !== null) { return this.formatDateTime(dateStart) } else if (dateStart !== null && dateEnd !== null) { if (this.$dateFns.isEqual(dateStart, dateEnd)) { return this.formatDateTime(dateStart) } else if (this.$dateFns.isSameDay(dateStart, dateEnd)) { return this.formatDate(dateStart, false) + ', ' + this.formatTime(dateStart) + ' - ' + this.formatTime(dateEnd) } else { return this.$t('from_day') + ' ' + this.formatDateTime(dateStart) + ' ' + this.$t('to_day') + ' ' + this.formatDateTime(dateEnd) } } return "" } }