|
| 1 | +/* eslint-disable no-underscore-dangle,no-param-reassign */ |
| 2 | +import dayjs from 'dayjs'; |
| 3 | +import isoWeek from 'dayjs/plugin/isoWeek'; // for isoWeekday functionality |
| 4 | +import customParseFormat from 'dayjs/plugin/customParseFormat'; // for parsing with format |
| 5 | +import { _adapters } from 'chart.js'; |
| 6 | + |
| 7 | +// Register required Day.js plugins |
| 8 | +dayjs.extend(isoWeek); |
| 9 | +dayjs.extend(customParseFormat); |
| 10 | + |
| 11 | +const FORMATS = { |
| 12 | + datetime: 'MMM D, YYYY, h:mm:ss a', |
| 13 | + millisecond: 'h:mm:ss.SSS a', |
| 14 | + second: 'h:mm:ss a', |
| 15 | + minute: 'h:mm a', |
| 16 | + hour: 'hA', |
| 17 | + day: 'MMM D', |
| 18 | + week: 'll', |
| 19 | + month: 'MMM YYYY', |
| 20 | + quarter: '[Q]Q - YYYY', |
| 21 | + year: 'YYYY', |
| 22 | +}; |
| 23 | + |
| 24 | +_adapters._date.override(typeof dayjs === 'function' ? { |
| 25 | + _id: 'dayjs', // DEBUG ONLY |
| 26 | + |
| 27 | + formats() { |
| 28 | + return FORMATS; |
| 29 | + }, |
| 30 | + |
| 31 | + parse(value, format) { |
| 32 | + if (typeof value === 'string' && typeof format === 'string') { |
| 33 | + value = dayjs(value, format); |
| 34 | + } else { |
| 35 | + value = dayjs(value); |
| 36 | + } |
| 37 | + return value.isValid() ? value.valueOf() : null; |
| 38 | + }, |
| 39 | + |
| 40 | + format(time, format) { |
| 41 | + return dayjs(time).format(format); |
| 42 | + }, |
| 43 | + |
| 44 | + add(time, amount, unit) { |
| 45 | + return dayjs(time).add(amount, unit).valueOf(); |
| 46 | + }, |
| 47 | + |
| 48 | + diff(max, min, unit) { |
| 49 | + return dayjs(max).diff(dayjs(min), unit); |
| 50 | + }, |
| 51 | + |
| 52 | + startOf(time, unit, weekday) { |
| 53 | + time = dayjs(time); |
| 54 | + if (unit === 'isoWeek') { |
| 55 | + // Day.js counts from 1 (Monday) to 7 (Sunday) |
| 56 | + weekday = Math.trunc(Math.min(Math.max(1, weekday || 1), 7)); |
| 57 | + return time.isoWeekday(weekday).startOf('day').valueOf(); |
| 58 | + } |
| 59 | + return time.startOf(unit).valueOf(); |
| 60 | + }, |
| 61 | + |
| 62 | + endOf(time, unit) { |
| 63 | + return dayjs(time).endOf(unit).valueOf(); |
| 64 | + }, |
| 65 | +} : {}); |
0 commit comments