{"version":3,"file":"date-time.mjs","names":[],"sources":["../../../../packages/util/date-time/time.ts","../../../../packages/util/date-time/picker.ts"],"sourcesContent":["import {\n  addDays,\n  endOfDay,\n  endOfMonth,\n  endOfWeek,\n  endOfYear,\n  parse,\n  parseISO,\n  startOfDay,\n  startOfMonth,\n  startOfWeek,\n  startOfYear,\n  subMonths,\n  subWeeks,\n  subYears,\n  format,\n  formatDistanceToNow\n} from 'date-fns';\n\nimport type { AlainThemePipeDateFormatCustom } from '@delon/util/config';\nimport type { NzSafeAny } from 'ng-zorro-antd/core/types';\nimport { DateLocale } from 'ng-zorro-antd/i18n';\n\n/**\n * Get the time range, return `[ Date, Date]` for the start and end dates\n *\n * 获取时间范围\n *\n * @param type 类型，带 `-` 表示过去一个时间，若指定 `number` 表示天数\n * @param time 开始时间\n * @param ignoreMaxTime 忽略追加结束日期的最大时间值\n */\nexport function getTimeDistance(\n  type: 'today' | '-today' | 'yesterday' | 'week' | '-week' | 'month' | '-month' | 'year' | '-year' | number,\n  time?: Date | string | number,\n  options?: { ignoreMaxTime?: boolean }\n): [Date, Date] {\n  time = time\n    ? typeof time === 'string'\n      ? parse(time, 'yyyy-MM-dd HH:mm:ss', new Date())\n      : new Date(time)\n    : new Date();\n  const opt: { weekStartsOn: 1 } = { weekStartsOn: 1 };\n\n  let res: [Date, Date];\n  switch (type) {\n    case 'today':\n      res = [time, time];\n      break;\n    case '-today':\n      res = [addDays(time, -1), time];\n      break;\n    case 'yesterday':\n      res = [addDays(time, -1), addDays(time, -1)];\n      break;\n    case 'week':\n      res = [startOfWeek(time, opt), endOfWeek(time, opt)];\n      break;\n    case '-week':\n      res = [startOfWeek(subWeeks(time, 1), opt), endOfWeek(subWeeks(time, 1), opt)];\n      break;\n    case 'month':\n      res = [startOfMonth(time), endOfMonth(time)];\n      break;\n    case '-month':\n      res = [startOfMonth(subMonths(time, 1)), endOfMonth(subMonths(time, 1))];\n      break;\n    case 'year':\n      res = [startOfYear(time), endOfYear(time)];\n      break;\n    case '-year':\n      res = [startOfYear(subYears(time, 1)), endOfYear(subYears(time, 1))];\n      break;\n    default:\n      res = type > 0 ? [time, addDays(time, type)] : [addDays(time, type), time];\n      break;\n  }\n  return options?.ignoreMaxTime ? res : fixEndTimeOfRange(res);\n}\n\n/**\n * fix time is the most, big value\n */\nexport function fixEndTimeOfRange(dates: [Date, Date]): [Date, Date] {\n  return [startOfDay(dates[0]), endOfDay(dates[1])];\n}\n\nexport interface ToDateOptions {\n  /** If parsing fails try to parse the date by pressing `formatString` */\n  formatString?: string;\n  /** If parsing fails returned default value, default: `new Date(NaN)` */\n  defaultValue?: NzSafeAny;\n  timestampSecond?: boolean;\n}\n\n/**\n * Convert to `Date` format\n *\n * @param value When is a number, it's treated as a timestamp; If it's seconds, you need to provide the `options.timestampSecond` parameter.\n */\nexport function toDate(value?: Date | string | number | null, options?: string | ToDateOptions): Date {\n  const { formatString, defaultValue, timestampSecond } = {\n    formatString: 'yyyy-MM-dd HH:mm:ss',\n    defaultValue: new Date(NaN),\n    timestampSecond: false,\n    ...(typeof options === 'string' ? { formatString: options } : options)\n  };\n  if (value == null) {\n    return defaultValue;\n  }\n  if (value instanceof Date) {\n    return value;\n  }\n  if (typeof value === 'number' || (typeof value === 'string' && /^[0-9]+$/.test(value))) {\n    const valueNumber = +value;\n    return new Date(timestampSecond ? valueNumber * 1000 : valueNumber);\n  }\n  let tryDate = parseISO(value);\n  if (isNaN(tryDate as NzSafeAny)) {\n    tryDate = parse(value, formatString!, new Date());\n  }\n\n  return isNaN(tryDate as NzSafeAny) ? defaultValue : tryDate;\n}\n\n/**\n * Format date, supports `Date, number, string` types\n *\n * @param value When is a number, it is treated as a timestamp (Support seconds and milliseconds timestamp).\n * @param formatString Please refer to [date-fnd format](https://date-fns.org/v2.30.0/docs/format) for string format\n * @param dateLocale Recommended to be consistent with NG-ZORRO by using `inject(NZ_DATE_LOCALE)`\n */\nexport function formatDate(\n  value: Date | string | number,\n  formatString: string,\n  options?: { locale?: DateLocale; customFormat?: AlainThemePipeDateFormatCustom }\n): string {\n  value = toDate(value);\n  if (isNaN(value as NzSafeAny)) return '';\n\n  const langOpt = { locale: options?.locale };\n  return formatString === 'fn'\n    ? formatDistanceToNow(value, langOpt)\n    : (options?.customFormat ?? format)(value, formatString, langOpt);\n}\n","import { addDays, addSeconds, differenceInCalendarDays, format } from 'date-fns';\n\nimport type { NzSafeAny } from 'ng-zorro-antd/core/types';\nimport type { DisabledDateFn, DisabledTimeConfig, DisabledTimeFn } from 'ng-zorro-antd/date-picker';\n\n// TODO: timezone process\nexport class DateTimePickerUtil {\n  /**\n   * Current local time\n   *\n   * 当前本地时间\n   */\n  get now(): Date {\n    return new Date();\n  }\n  /**\n   * Current local date (not including time part)\n   *\n   * 当前本地日期（不包含时间部分）\n   */\n  get date(): Date {\n    return this.removeTime(this.now);\n  }\n  /**\n   * Remove the time part of the date\n   *\n   * 移除日期的时间部分\n   */\n  removeTime(d: Date): Date {\n    return new Date(d.toDateString());\n  }\n  /**\n   * Format date-time\n   *\n   * 格式化日期\n   */\n  format(d: number | Date, formatString: string = 'yyyy-MM-dd HH:mm:ss'): string {\n    return format(d, formatString);\n  }\n  private genTick(count: number): number[] {\n    return new Array(count).fill(0).map((_, idx) => idx);\n  }\n  /**\n   * Calculate the number of days between two dates, `0` means the same day\n   *\n   * 计算两个日期相差天数，`0` 表示同一天\n   */\n  getDiffDays(dateLeft: Date | number, dateRight?: Date | number): number {\n    return differenceInCalendarDays(\n      dateLeft,\n      typeof dateRight === 'number' ? addDays(this.date, dateRight) : (dateRight ?? this.date)\n    );\n  }\n  /**\n   * Disabled Before date (Default: today), Generally serves `nzDisabledDate`\n   *\n   * 禁用之前日期（默认：今天），一般服务于 `nzDisabledDate`\n   */\n  disabledBeforeDate(options?: { offsetDays?: Date | number }): DisabledDateFn {\n    return (d): boolean => this.getDiffDays(d, options?.offsetDays) < 0;\n  }\n  /**\n   * Disabled After date (Default: today), Generally serves `nzDisabledDate`\n   *\n   * 禁用之后日期（默认：今天），一般服务于 `nzDisabledDate`\n   */\n  disabledAfterDate(options?: { offsetDays?: Date | number }): DisabledDateFn {\n    return (d): boolean => this.getDiffDays(d, options?.offsetDays) > 0;\n  }\n  private baseDisabledTime(type: 'before' | 'after', offsetSeconds?: number): DisabledTimeFn {\n    const tick24 = this.genTick(24);\n    const tick60 = this.genTick(60);\n    return (current): DisabledTimeConfig => {\n      const cur = current as Date;\n      if (cur == null) {\n        return {} as NzSafeAny;\n      }\n      const now = addSeconds(this.now, offsetSeconds ?? 0);\n      const nowHours = now.getHours();\n      const nowMinutes = now.getMinutes();\n      const curHours = cur.getHours();\n      const isToday = this.getDiffDays(this.removeTime(cur)) === 0;\n      return {\n        nzDisabledHours: () => {\n          if (!isToday) return [];\n          return type === 'before' ? tick24.slice(0, nowHours) : tick24.slice(nowHours + 1);\n        },\n        nzDisabledMinutes: () => {\n          if (isToday && curHours === nowHours) {\n            return type === 'before' ? tick60.slice(0, nowMinutes) : tick60.slice(nowMinutes + 1);\n          }\n          return [];\n        },\n        nzDisabledSeconds: () => {\n          if (isToday && curHours === nowHours && cur.getMinutes() === nowMinutes) {\n            const nowSeconds = now.getSeconds();\n            return type === 'before' ? tick60.slice(0, nowSeconds) : tick60.slice(nowSeconds + 1);\n          }\n          return [];\n        }\n      };\n    };\n  }\n  /**\n   * Disabled Before time (Default: now), Generally serves `nzDisabledTime`\n   *\n   * 禁用之前时间（默认：现在），一般服务于 `nzDisabledTime`\n   */\n  disabledBeforeTime(options?: { offsetSeconds?: number }): DisabledTimeFn {\n    return this.baseDisabledTime('before', options?.offsetSeconds);\n  }\n  /**\n   * Disabled After time (Default: now), Generally serves `nzDisabledTime`\n   *\n   * 禁用之后时间（默认：现在），一般服务于 `nzDisabledTime`\n   */\n  disabledAfterTime(options?: { offsetSeconds?: number }): DisabledTimeFn {\n    return this.baseDisabledTime('after', options?.offsetSeconds);\n  }\n}\n\nexport const dateTimePickerUtil = new DateTimePickerUtil();\n"],"mappings":";AAgCA,S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