dateUtils.ts 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import { format, parse } from 'date-fns';
  2. import locale from "date-fns/locale/fr";
  3. export default class DatesUtils {
  4. private $dateFns: dateFns;
  5. private $t: any
  6. private $i18n: any
  7. private ISO_FORMAT = 'yyyy-MM-dd';
  8. constructor(dateFns: dateFns, t: any, i18n: any) {
  9. this.$dateFns = dateFns
  10. this.$t = t
  11. this.$i18n = i18n
  12. }
  13. formatIso(date: Date): string {
  14. return format(date, this.ISO_FORMAT)
  15. }
  16. today(): Date {
  17. return new Date()
  18. }
  19. todayIso(): string {
  20. return this.formatIso(this.today())
  21. }
  22. formatIsoDate(date: string, fmt: string): string {
  23. return format(parse(date, this.ISO_FORMAT, new Date()), fmt);
  24. }
  25. reformatDate(date: string, fromFormat: string, toFormat: string): string {
  26. return format(parse(date, fromFormat, new Date()), toFormat);
  27. }
  28. formatDate(date: Date, short = true): string {
  29. return short ? this.$dateFns.format(date, 'dd/MM/yyyy') : this.$dateFns.format(date, 'dd MMM yyyy', {locale: locale})
  30. }
  31. formatTime(date: Date): string {
  32. return this.$dateFns.format(date, "HH'h'mm")
  33. }
  34. formatDateTime(date: Date): string {
  35. return this.formatDate(date) + ' ' + this.$t('on_hour') + ' ' + this.formatTime(date)
  36. }
  37. formatDateIntervalFor(dateStart: Date | null = null, dateEnd: Date | null = null): string {
  38. if (dateStart === null && dateEnd !== null) {
  39. return this.formatDateTime(dateEnd)
  40. } else if (dateEnd === null && dateStart !== null) {
  41. return this.formatDateTime(dateStart)
  42. } else if (dateStart !== null && dateEnd !== null) {
  43. if (this.$dateFns.isEqual(dateStart, dateEnd)) {
  44. return this.formatDateTime(dateStart)
  45. } else if (this.$dateFns.isSameDay(dateStart, dateEnd)) {
  46. return this.formatDate(dateStart, false) + ', ' +
  47. this.formatTime(dateStart) + ' - ' + this.formatTime(dateEnd)
  48. } else {
  49. return this.$t('from_day') + ' ' + this.formatDateTime(dateStart) + ' ' + this.$t('to_day') + ' ' + this.formatDateTime(dateEnd)
  50. }
  51. }
  52. return ""
  53. }
  54. }