All files / app/src/shared/helpers date.helpers.ts

28.57% Statements 56/196
25% Branches 6/24
28.57% Functions 6/21
28.57% Lines 56/196

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 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 2371x           1x 1x 1x                 1x                             1x                     1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x                         1x                     1x                 1x               1x           1x 2x 2x   1x 32x 32x                           32x                           32x   1x 48x 48x 48x     48x                   1x           1x           1x 2x 2x 2x 2x 2x             2x 2x 2x     2x                     1x 1x 16x               16x 16x 16x   1x                             1x                 1x        
import dayjs, { Dayjs } from 'dayjs'
import { EventValue, RangeValue } from 'rc-picker/lib/interface'
import { BaseFilter, FormatDate, Nullable, SelectOption, TFunction } from '../@types'
import utc from 'dayjs/plugin/utc'
import { DATE_FILTER_FORMAT } from '@/shared/config'
 
dayjs.extend(utc)
export const setDateRange =
  (
    setStartDate: (value: EventValue<Dayjs> | undefined) => void,
    setEndDate: (value: EventValue<Dayjs> | undefined) => void
  ) =>
  (range: RangeValue<Dayjs>) => {
    setStartDate(range?.[0])
    setEndDate(range?.[1])
  }
 
export const getMonthSelectOptions = (t: TFunction): SelectOption<number>[] => [
  { id: 1, label: t('january') },
  { id: 2, label: t('february') },
  { id: 3, label: t('march') },
  { id: 4, label: t('april') },
  { id: 5, label: t('may') },
  { id: 6, label: t('june') },
  { id: 7, label: t('july') },
  { id: 8, label: t('august') },
  { id: 9, label: t('september') },
  { id: 10, label: t('october') },
  { id: 11, label: t('november') },
  { id: 12, label: t('december') },
]
 
export const getAgeBetweenTwoDates = (date: string, t: TFunction) => {
  if (!date) return '-'
 
  const diffInMonths = dayjs().utc().diff(date, 'month') % 12
  const diffInYears = dayjs().utc().diff(date, 'year')
 
  return diffInYears
    ? `${diffInYears} ${t('common:year')} ${diffInMonths} ${t('common:month')}`
    : `${diffInMonths} ${t('common:month')}`
}
 
export const getAgeFromDate = (date: string, t: TFunction) => {
  const startDate = dayjs(date)
  const endDate = dayjs()
  const years = endDate.diff(startDate, 'year')
  const months = endDate.diff(startDate, 'month') - years * 12
  let result = ''
  if (years) result += `${years} ${t('common:y')}`
  if (years && months) result += ' '
  if (months) result += `${months} ${t('common:m’th')}`
  return result || '-'
}
 
export const transformYearToDataForFilter = (
  date: string | Nullable<BaseFilter>,
  params?: {
    month?: number
    day?: number
  }
) => {
  if (typeof date == 'string') {
    const numbersOnly = date.replace(/\D/g, '')
    return new Date(Number(numbersOnly), params?.month || 0, params?.day || 2)
  }
}
 
export const getEndDate = (date: string) => {
  const formattedDate = new Date(date)
 
  formattedDate.setHours(23, 59, 59, 999)
 
  return formattedDate?.toISOString()
}
 
export type DatePeriod = 'day' | 'month'
 
// Функция для получения 23:59 последнего дня месяца в формате UTC
export function getLastDayOfMonthUTC(initialDate: Date): Date {
  const year = initialDate.getFullYear()
  const month = initialDate.getMonth() + 1
  const date = new Date(Date.UTC(year, month, 0)) // Нулевой день следующего месяца - это последний день текущего месяца
  date.setUTCHours(23, 59, 59, 999) // Устанавливаем время 23:59:59.999
  return date
}
 
// Функция для получения 00:00 первого дня месяца в формате UTC
export function getFirstDayOfMonthUTC(initialDate: Date): Date {
  const year = initialDate.getFullYear()
  const month = initialDate.getMonth() + 1
  const date = new Date(Date.UTC(year, month - 1, 1)) // Первый день текущего месяца
  date.setUTCHours(0, 0, 0, 0) // Устанавливаем время 00:00:00.000
  return date
}
 
export const getEndTimeDay = (date: string) => {
  const formatedDay = new Date(date)
  formatedDay.setUTCHours(23, 59, 59)
  return formatedDay.toISOString()
}
 
export const removeTimezone = (date: string) => {
  return new Date(date).toISOString().split('T')[0]
}
 
export const getAfterAndBeforeDate = (date: Nullable<string>, config?: { period?: DatePeriod }) => {
  if (!date) return null
  if (!config?.period || config.period === 'month') {
    const beforeDate = new Date(date)
    const beforeDateFormated = getFirstDayOfMonthUTC(beforeDate)
    beforeDateFormated.setUTCHours(0, 0, 0, 0)
 
    const afterDate = new Date(date)
    const afterDateFormated = getLastDayOfMonthUTC(afterDate)
    afterDateFormated.setUTCHours(23, 59, 59, 999)
 
    return {
      after: beforeDateFormated.toISOString(),
      before: afterDateFormated.toISOString(),
    }
  }
  if (config?.period === 'day') {
    const beforeDate = new Date(date)
    beforeDate.setDate(beforeDate.getDate() + 1)
    beforeDate.setUTCHours(0, 0, 0, 0)
 
    const afterDate = new Date(date)
    afterDate.setDate(afterDate.getDate() - 1)
    afterDate.setUTCHours(23, 59, 59, 999)
 
    return {
      after: afterDate.toISOString(),
      before: beforeDate.toISOString(),
    }
  }
}
 
export const getRangeFilter = (dates: Nullable<string[]>, filterName: string) => {
  if (!dates) return null
  if ((dates.length === 2 && !dates[1]) || dates.length === 1)
    return {
      [`${filterName}[gte]`]: dates[0],
    }
  if (dates.length === 2 && !dates[0]) {
    return {
      [`${filterName}[lte]`]: dates[1],
    }
  }
  return {
    [`${filterName}[between]`]: `${dates[0]}..${dates[1]}`,
  }
}
 
export const getEndOfDay = (date: string) => {
  const formattedDate = dayjs(date).local()
  const endOfDay = formattedDate.hour(23).minute(59).second(59)
  return endOfDay.format(DATE_FILTER_FORMAT)
}
 
export const getStarOfDay = (date: string) => {
  const formattedDate = dayjs(date).local()
  const startOfDay = formattedDate.hour(0).minute(0).second(0)
  return startOfDay.format(DATE_FILTER_FORMAT)
}
 
export const getRangeFilterWithAfterAndBefore = (
  dates: Nullable<string[]>,
  filterBefore: string,
  filterAfter: string
) => {
  const resetTime = (date: string, filter: string) => {
    if (filter.includes('after')) {
      return getStarOfDay(date)
    } else {
      return getEndOfDay(date)
    }
  }
  if (!dates) return null
  if ((dates.length === 2 && !dates[1]) || dates.length === 1)
    return {
      [`${filterAfter}`]: resetTime(dates[0], filterAfter),
    }
  if (dates.length === 2 && !dates[0]) {
    return {
      [`${filterBefore}`]: resetTime(dates[1], filterBefore),
    }
  }
  return {
    [`${filterAfter}`]: resetTime(dates[0], filterAfter),
    [`${filterBefore}`]: resetTime(dates[1], filterBefore),
  }
}
 
const currentDate = dayjs()
export const getDateRange = (ages: Nullable<string[]>, filterBefore: string, filterAfter: string) => {
  if (!ages) return null
  const getCurrentDateFilter = (month: string, day: number) => {
    const date = currentDate.subtract(Number(month), 'month').toDate()
    date.setDate(day)
    return date
  }
  return {
    ...(ages[0] && { [`${filterBefore}`]: getCurrentDateFilter(ages[0], 30).toISOString() }),
    ...(ages[1] && { [`${filterAfter}`]: getCurrentDateFilter(ages[1], 1).toISOString() }),
  }
}
 
export const getDateFromDays = (days: string[], afterFilter: string, beforeFilter: string) => {
  const getDate = (day: string, dayInitial: number) => {
    const date = currentDate.add(Number(day || ''), 'day').toDate()
    date.setDate(dayInitial)
    return date
  }
  const after = getDate(days?.[0] || '', 1)?.toISOString()
  const before = getDate(days?.[1] || '', 30)?.toISOString()
 
  return {
    ...(days?.[1] && { [`${beforeFilter}`]: before }),
    ...(days?.[0] && { [`${afterFilter}`]: after }),
  }
}
 
export const getDateFormat = (key: string): FormatDate => {
  if (key === 'manufactureDate') return FormatDate.MONTH_YEAR
  if (key === 'dateOperation') return FormatDate.DAY
  if (key === 'date') return FormatDate.DAY
  if (key.includes('Year')) return FormatDate.YEAR
  if (key.includes('Date')) return FormatDate.DAY
  return FormatDate.MONTH_YEAR
}
 
export const getDateForYear = (year: string, month?: string) => {
  const date = new Date(parseInt(year), month ? parseInt(month) - 1 : 0, 31, 1, 1, 1).toISOString()
  return date
}