dateUtils.ts 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import { format } from 'date-fns'
  2. import type { Locale } from 'date-fns'
  3. import { enUS, fr } from 'date-fns/locale'
  4. import ArrayUtils from '~/services/utils/arrayUtils'
  5. export const enum supportedLocales {
  6. FR = 'fr',
  7. EN = 'en',
  8. }
  9. const defaultLocale = 'fr'
  10. export default class DateUtils {
  11. public static format(date: Date, fmt: string): string {
  12. return format(date, fmt)
  13. }
  14. /**
  15. * Formate la ou les dates au format donné et retourne la liste concaténée
  16. *
  17. * @param dates
  18. * @param fmt
  19. * @param sep
  20. */
  21. public static formatAndConcat(
  22. dates: Date | Array<Date>,
  23. fmt: string,
  24. sep: string = ' - '
  25. ): string {
  26. dates = Array.isArray(dates) ? dates : [dates]
  27. return dates.map((d) => this.format(d, fmt)).join(sep)
  28. }
  29. /**
  30. * Trie les dates par ordre chronologique
  31. *
  32. * @param dates
  33. * @param reverse
  34. */
  35. public static sort(
  36. dates: Array<Date>,
  37. reverse: boolean = false
  38. ): Array<Date> {
  39. return ArrayUtils.sort(dates, reverse) as Array<Date>
  40. }
  41. public static getFnsLocale(code: supportedLocales): Locale {
  42. const mapping = {
  43. en: enUS,
  44. fr,
  45. }
  46. return mapping[code] ?? mapping[defaultLocale]
  47. }
  48. public static getShortFormatPattern(code: supportedLocales): string {
  49. const mapping = {
  50. en: 'MM/dd/yyyy',
  51. fr: 'dd/MM/yyyy',
  52. }
  53. return mapping[code] ?? mapping[defaultLocale]
  54. }
  55. public static getFormatPattern(code: supportedLocales): string {
  56. const mapping = {
  57. en: 'MM/dd/yyyy HH:mm',
  58. fr: 'dd/MM/yyyy HH:mm',
  59. }
  60. return mapping[code] ?? mapping[defaultLocale]
  61. }
  62. public static formatIsoShortDate(date: Date): string {
  63. return format(date, 'yyyy-MM-dd')
  64. }
  65. }