Skip to content

Commit eb49a75

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

File tree

2 files changed

+29
-6
lines changed

2 files changed

+29
-6
lines changed

src/scales/scale.time.js

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

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

408433
var defaultConfig = {
@@ -621,6 +646,7 @@ module.exports = function(Chart) {
621646
me._majorUnit = determineMajorUnit(me._unit);
622647
me._table = buildLookupTable(me._timestamps.data, min, max, options.distribution);
623648
me._offsets = computeOffsets(me._table, ticks, min, max, options);
649+
me._labelFormat = determineLabelFormat(me._timestamps.data, timeOpts);
624650

625651
return ticksFromTimestamps(ticks, me._majorUnit);
626652
},
@@ -635,11 +661,8 @@ module.exports = function(Chart) {
635661
if (helpers.isObject(value)) {
636662
label = me.getRightValue(value);
637663
}
638-
if (timeOpts.tooltipFormat) {
639-
label = momentify(label, timeOpts).format(timeOpts.tooltipFormat);
640-
}
641664

642-
return label;
665+
return momentify(label, timeOpts).format(me._labelFormat);
643666
},
644667

645668
/**

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)