dateUtils.ts 1.6 KB

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