Skip to content

Instantly share code, notes, and snippets.

@commis1059
Created April 21, 2020 07:27
Show Gist options
  • Save commis1059/b7a1244eae8d9235e0329d9106de5da6 to your computer and use it in GitHub Desktop.
Save commis1059/b7a1244eae8d9235e0329d9106de5da6 to your computer and use it in GitHub Desktop.
Chart.js date adapter using dayjs (UTC Version)
import Chart from 'chart.js'
import dayjs from 'dayjs'
import customParseFormat from 'dayjs/plugin/customParseFormat'
import isoWeek from 'dayjs/plugin/isoWeek'
import utc from 'dayjs/plugin/utc'
dayjs.extend(customParseFormat)
dayjs.extend(isoWeek)
dayjs.extend(utc)
const FORMATS = {
datetime: 'MMM D, YYYY, h:mm:ss a',
millisecond: 'h:mm:ss.SSS a',
second: 'h:mm:ss a',
minute: 'h:mm a',
hour: 'hA',
day: 'MMM D',
week: 'll',
month: 'MMM YYYY',
quarter: '[Q]Q - YYYY',
year: 'YYYY',
}
Chart._adapters._date.override({
_id: 'dayjs-utc', // DEBUG ONLY
formats: function() {
return FORMATS
},
parse: function(value, format) {
if (Chart.helpers.isNullOrUndef(value)) return null
if (typeof value === 'string' && typeof format === 'string') {
value = dayjs.utc(value, format)
} else if (!(value instanceof dayjs)) {
value = dayjs.utc(value)
}
return value.isValid() ? value.valueOf() : null
},
format: function(time, format) {
return dayjs.utc(time).format(format)
},
add: function(time, amount, unit) {
return dayjs.utc(time).add(amount, unit).valueOf()
},
diff: function(max, min, unit) {
return dayjs.utc(max).diff(dayjs.utc(min), unit)
},
startOf: function(time, unit, weekday) {
if (unit === 'isoWeek') return dayjs.utc(time).isoWeekday(weekday).valueOf()
return dayjs.utc(time).startOf(unit).valueOf()
},
endOf: function(time, unit) {
return dayjs.utc(time).endOf(unit).valueOf()
},
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment