From ccc2f5b90cdaeb4875371e963854e131ea44ea17 Mon Sep 17 00:00:00 2001 From: Ben McCann Date: Wed, 27 Dec 2017 17:25:07 -0800 Subject: [PATCH] Format the label in the time scale tooltip --- src/scales/scale.time.js | 32 +++++++++++++++++++++++++++++--- 1 file changed, 29 insertions(+), 3 deletions(-) diff --git a/src/scales/scale.time.js b/src/scales/scale.time.js index 90904f9e6f0..3275c72a5a0 100644 --- a/src/scales/scale.time.js +++ b/src/scales/scale.time.js @@ -403,6 +403,31 @@ function ticksFromTimestamps(values, majorUnit) { return ticks; } +function determineLabelFormat(data, timeOpts) { + var i, momentDate, hasTime; + var ilen = data.length; + + if (timeOpts.tooltipFormat) { + return timeOpts.tooltipFormat; + } + + // find the label with the most parts (milliseconds, minutes, etc.) + // format all labels with the same level of detail as the most specific label + for (i = 0; i < ilen; i++) { + momentDate = momentify(data[i], timeOpts); + if (momentDate.millisecond() !== 0) { + return 'MMM D, YYYY h:mm:ss.SSS a'; + } + if (momentDate.second() !== 0 || momentDate.minute() !== 0 || momentDate.hour() !== 0) { + hasTime = true; + } + } + if (hasTime) { + return 'MMM D, YYYY h:mm:ss a'; + } + return 'MMM D, YYYY'; +} + module.exports = function(Chart) { var defaultConfig = { @@ -621,6 +646,7 @@ module.exports = function(Chart) { me._majorUnit = determineMajorUnit(me._unit); me._table = buildLookupTable(me._timestamps.data, min, max, options.distribution); me._offsets = computeOffsets(me._table, ticks, min, max, options); + me._labelFormat = determineLabelFormat(me._timestamps.data, timeOpts); return ticksFromTimestamps(ticks, me._majorUnit); }, @@ -635,11 +661,11 @@ module.exports = function(Chart) { if (helpers.isObject(value)) { label = me.getRightValue(value); } - if (timeOpts.tooltipFormat) { - label = momentify(label, timeOpts).format(timeOpts.tooltipFormat); + if (typeof label === 'string') { + return label; } - return label; + return momentify(label, timeOpts).format(me._labelFormat); }, /**