dateUtils.ts 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import { format } from 'date-fns'
  2. import { enUS, fr } from 'date-fns/locale'
  3. import ArrayUtils from '~/services/utils/arrayUtils'
  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(
  21. dates: Date | Array<Date>,
  22. fmt: string,
  23. sep: string = ' - ',
  24. ): string {
  25. dates = Array.isArray(dates) ? dates : [dates]
  26. return dates.map((d) => this.format(d, fmt)).join(sep)
  27. }
  28. /**
  29. * Trie les dates par ordre chronologique
  30. *
  31. * @param dates
  32. * @param reverse
  33. */
  34. public static sort(
  35. dates: Array<Date>,
  36. reverse: boolean = false,
  37. ): Array<Date> {
  38. return ArrayUtils.sort(dates, reverse) as Array<Date>
  39. }
  40. public static getFnsLocale(code: supportedLocales): Locale {
  41. // noinspection TypeScriptUnresolvedReference
  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. }