# All files / src/_utils dateTime.ts

88.88% Statements 40/45
81.81% Branches 9/11
87.5% Functions 14/16
88.09% Lines 37/42

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    12713x

    13x
    13x

    13x

    13x
    1399x

    13x

    13x
    5x
    5x

    5x

    710x
    710x

    4814x
    710x

    13x

    1x

    13x

    724x

    711x
    1x

    710x
    710x

    710x

    1x

    1x
    1x

    1413x

    13x
    11x
    2x

    9x
    3x

    6x

    6x

    13x
    4x

     import {
      DateTimeFormatter,
      DateTimeOptions,
    } from '@procore/globalization-toolkit'
    import * as R from 'ramda'
    import { getFormatterLocale } from './i18n'

    const dateTimePresets = {
      time: {
        hour: 'numeric',
        minute: 'numeric',
        timeZoneName: 'short',
      } as Intl.DateTimeFormatOptions,
      'abbr-weekday-abbr-date': {
        weekday: 'short',
        year: 'numeric',
        month: 'short',
        day: 'numeric',
      } as Intl.DateTimeFormatOptions,
      date: {
        year: 'numeric',
        month: 'long',
        day: 'numeric',
      } as Intl.DateTimeFormatOptions,
      'weekday-date': {
        weekday: 'long',
        year: 'numeric',
        month: 'long',
        day: 'numeric',
      } as Intl.DateTimeFormatOptions,
      none: {} as Intl.DateTimeFormatOptions,
      'numeric-date': {
        year: 'numeric',
        month: 'numeric',
        day: 'numeric',
      } as Intl.DateTimeFormatOptions,
    }

    export type IntlDateTimeOptionPresets = keyof typeof dateTimePresets

    export const getPresetDateTimeOptions = (type: IntlDateTimeOptionPresets) => {
      return dateTimePresets[type] || dateTimePresets.none
    }

    const pseudoDate = (date: string) => date.replace(/[\/\-\,\:]/g, '.')

    const pseudoFormatPart = ({
      type,
      value,
    }: Intl.DateTimeFormatPart): Intl.DateTimeFormatPart =>
      type === 'literal' ? { type, value: '.' } : { type, value }

    function formatterFactory(
      formatterLocale: string,
      options: Intl.DateTimeFormatOptions
    ): DateTimeFormatter {
      try {
        return new DateTimeFormatter(transformDateOptions(formatterLocale, options))
      } catch (error) {
        console.error(
          `@procore/core-react Intl.DateTimeFormat error for locale ${formatterLocale}. Will fall back to en-US`,
          error
        )
        return new DateTimeFormatter(transformDateOptions('en-US', options))
      }
    }

    function transformDateOptions(
      formatterLocale: string,
      options: Intl.DateTimeFormatOptions
    ): DateTimeOptions {
      const isDefined = (val: string | undefined) => val !== undefined
      return R.pickBy(isDefined, { ...{ locale: formatterLocale }, ...options })
    }

    const mapFormatToParts = (
      parts: Intl.DateTimeFormatPart[]
    ): Intl.DateTimeFormatPart[] => parts.map(pseudoFormatPart)

    export function intlDateTimeFormat(
      locale: string,
      options: Intl.DateTimeFormatOptions = {}
    ) {
      if (!locale) {
        throw new Error('Locale is a required parameter.')
      }
      const formatterLocale = getFormatterLocale(locale)
      const formatter = formatterFactory(formatterLocale, options)

      return locale === 'pseudo'
        ? {
            format: (date: Date) => pseudoDate(formatter.formatDateTime(date)),
            formatToParts: (date: Date) =>
              mapFormatToParts(formatter.formatDateTimeToParts(date)),
            resolvedOptions: () => formatter.formatter.resolvedOptions(),
          }
        : {
            format: (date: Date) => formatter.formatDateTime(date),
            formatToParts: (date: Date) => formatter.formatDateTimeToParts(date),
            resolvedOptions: () => formatter.formatter.resolvedOptions(),
          }
    }

    export function toDate(date: string | Date, log?: string) {
      if (date instanceof Date) {
        return date
      }
      if (!isNaN(Date.parse(date))) {
        return new Date(date)
      }
      Iif (log) {
        console.warn(
          `@procore/core-react: ${log}; toDate invalid date format`,
          date
        )
      }
      return date as any as Date
    }

    // Date should already be shifted to the time zone, meaning we already have the date in location and
    // now we need it in a specific style https://developer.mozilla.org/en-US/docs/Web/HTML/Element/time#valid_datetime_values
    // toLocaleDateString uses Intl DateTimeFormat
    // alternative toLocaleDateString('en-GB', { timeZone })
    export function formatMachineDate(date: Date) {
      return date.toLocaleDateString('en-GB').split('/').reverse().join('-')
    }