import endsWith from 'lodash/endsWith'
import parse from 'date-fns/parse'

const dateFormats = {
  withTimezone: 'yyyy-MM-dd HH:mm:ssx',
  withoutTimezone: 'yyyy-MM-dd HH:mm:ss',
}

export const parseDate = (
  dateString: string,
  format?: string,
) => {
  const defaultFormat = endsWith(dateString, 'Z')
    ? dateFormats.withTimezone
    : dateFormats.withoutTimezone
  return parse(
    dateString,
    format ?? defaultFormat,
    new Date(),
  )
}
