Skip to content

Commit

Permalink
Add format method to time scale to format timestamp using scale optio…
Browse files Browse the repository at this point in the history
…ns (#11063)
  • Loading branch information
stockiNail committed Jan 18, 2023
1 parent 997eab4 commit e8d9fb5
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 0 deletions.
13 changes: 13 additions & 0 deletions src/scales/scale.time.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions src/types/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3270,6 +3270,7 @@ export type TimeScaleOptions = Omit<CartesianScaleOptions, 'min' | 'max'> & {
};

export interface TimeScale<O extends TimeScaleOptions = TimeScaleOptions> extends Scale<O> {
format(value: number, format?: string): string;
getDataTimestamps(): number[];
getLabelTimestamps(): string[];
normalize(values: number[]): number[];
Expand Down
43 changes: 43 additions & 0 deletions test/specs/scale.time.tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down

0 comments on commit e8d9fb5

Please sign in to comment.