Skip to content

Commit 9be0d46

Browse files
committed
Format the label in the time scale tooltip
1 parent 92d033b commit 9be0d46

File tree

2 files changed

+31
-6
lines changed

2 files changed

+31
-6
lines changed

src/scales/scale.time.js

Lines changed: 29 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -403,6 +403,33 @@ function ticksFromTimestamps(values, majorUnit) {
403403
return ticks;
404404
}
405405

406+
function determineLabelFormat(data, timeOpts) {
407+
var i, momentDate, hasMillis, hasTime;
408+
409+
if (timeOpts.tooltipFormat) {
410+
return timeOpts.tooltipFormat;
411+
}
412+
413+
// find the label with the most parts (milliseconds, minutes, etc.)
414+
// format all labels with the same level of detail as the most specific label
415+
for (i = 0; i < data.length; i++) {
416+
momentDate = momentify(data[i], timeOpts);
417+
if (momentDate.millisecond() !== 0) {
418+
hasMillis = true;
419+
break;
420+
}
421+
if (momentDate.second() !== 0 || momentDate.minute() !== 0 || momentDate.hour() !== 0) {
422+
hasTime = true;
423+
}
424+
}
425+
if (hasMillis) {
426+
return 'MMM D, YYYY h:mm:ss.SSS a';
427+
} else if (hasTime) {
428+
return 'MMM D, YYYY h:mm:ss a';
429+
}
430+
return 'MMM D, YYYY';
431+
}
432+
406433
module.exports = function(Chart) {
407434

408435
var defaultConfig = {
@@ -621,6 +648,7 @@ module.exports = function(Chart) {
621648
me._majorUnit = determineMajorUnit(me._unit);
622649
me._table = buildLookupTable(me._timestamps.data, min, max, options.distribution);
623650
me._offsets = computeOffsets(me._table, ticks, min, max, options);
651+
me._labelFormat = determineLabelFormat(me._timestamps.data, timeOpts);
624652

625653
return ticksFromTimestamps(ticks, me._majorUnit);
626654
},
@@ -635,11 +663,8 @@ module.exports = function(Chart) {
635663
if (helpers.isObject(value)) {
636664
label = me.getRightValue(value);
637665
}
638-
if (timeOpts.tooltipFormat) {
639-
label = momentify(label, timeOpts).format(timeOpts.tooltipFormat);
640-
}
641666

642-
return label;
667+
return momentify(label, timeOpts).format(me._labelFormat);
643668
},
644669

645670
/**

test/specs/scale.time.tests.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -580,8 +580,8 @@ describe('Time scale tests', function() {
580580

581581
var xScale = chart.scales.xScale0;
582582
expect(xScale.getLabelForIndex(0, 0)).toBeTruthy();
583-
expect(xScale.getLabelForIndex(0, 0)).toBe('2015-01-01T20:00:00');
584-
expect(xScale.getLabelForIndex(6, 0)).toBe('2015-01-10T12:00');
583+
expect(xScale.getLabelForIndex(0, 0)).toBe('Jan 1, 2015 8:00:00 pm');
584+
expect(xScale.getLabelForIndex(6, 0)).toBe('Jan 10, 2015 12:00:00 pm');
585585
});
586586

587587
it('should get the correct pixel for only one data in the dataset', function() {

0 commit comments

Comments
 (0)