diff --git a/src/scales/scale.time.js b/src/scales/scale.time.js index 6f292beacd2..522f5d32c43 100644 --- a/src/scales/scale.time.js +++ b/src/scales/scale.time.js @@ -502,6 +502,19 @@ export default class TimeScale extends Scale { return adapter.format(value, timeOpts.displayFormats.datetime); } + /** + * @param {number} value + * @param {string|undefined} format + * @return {string} + */ + format(value, format) { + const options = this.options; + const formats = options.time.displayFormats; + const unit = this._unit; + const fmt = format || formats[unit]; + return this._adapter.format(value, fmt); + } + /** * Function to format an individual tick mark * @param {number} time diff --git a/src/types/index.d.ts b/src/types/index.d.ts index c302c34389c..f312dc4114b 100644 --- a/src/types/index.d.ts +++ b/src/types/index.d.ts @@ -3270,6 +3270,7 @@ export type TimeScaleOptions = Omit & { }; export interface TimeScale extends Scale { + format(value: number, format?: string): string; getDataTimestamps(): number[]; getLabelTimestamps(): string[]; normalize(values: number[]): number[]; diff --git a/test/specs/scale.time.tests.js b/test/specs/scale.time.tests.js index abae7359cf3..42817ae15c9 100644 --- a/test/specs/scale.time.tests.js +++ b/test/specs/scale.time.tests.js @@ -413,6 +413,49 @@ describe('Time scale tests', function() { expect(xScale.getLabelForValue(value)).toBe('Jan 1, 2015, 8:00:00 pm'); }); + it('should get the correct label for a data value by format', function() { + var chart = window.acquireChart({ + type: 'line', + data: { + datasets: [{ + xAxisID: 'x', + data: [null, 10, 3] + }], + labels: ['2015-01-01T20:00:00', '2015-01-02T21:00:00', '2015-01-03T22:00:00', '2015-01-05T23:00:00', '2015-01-07T03:00', '2015-01-08T10:00', '2015-01-10T12:00'], // days + }, + options: { + scales: { + x: { + type: 'time', + time: { + unit: 'day', + displayFormats: { + day: 'YYYY-MM-DD' + } + }, + position: 'bottom', + ticks: { + source: 'labels', + autoSkip: false + } + } + } + } + }); + + var xScale = chart.scales.x; + for (const lbl of chart.data.labels) { + var dd = xScale._adapter.parse(lbl); + var parsed = lbl.split('T'); + expect(xScale.format(dd)).toBe(parsed[0]); + } + for (const lbl of chart.data.labels) { + var mm = xScale._adapter.parse(lbl); + var yearMonth = lbl.substring(0, 7); + expect(xScale.format(mm, 'YYYY-MM')).toBe(yearMonth); + } + }); + it('should round to isoWeekday', function() { var chart = window.acquireChart({ type: 'line',