Sathy
Sathy

Reputation: 303

Javascript - Convert timestamp into milliseconds for Highcharts Y axis

Please help me in converting the string into time format[Hr:Min:Sec]

Here is my piece

seriesData_1.push(parseFloat($(this).attr('myVar')));

I have tried changing this to:

seriesData_1.push(Date.parse("1-1-1" + ($(this).attr('myVar'))));

but no luck. The myVar will be holding the value 20:57:13

Update : I was so dumb in Highcharts & Javascript and with Stackoverflow guidance, I got what I want.

Here it is. I have got a series myVar holding values like 20:57:13 etc in Hr:Min:Sec format which needed to be plotted in Y axis. Got to know that we have got datetime type in Y axis which can plot the graph for you. But for that you need to get your timestamp converted into milliseconds.

And this is what I have done for that

yourtime = $(this).attr('myVar');
hms = yourtime.split(':');
msecs = hms[0] * 3600000 + hms[1] * 60000 + hms[2]*1000;
seriesData_1.push(msecs);

Now I have got it converted into milliseconds, to get this plotted in Y axis with H:M:S format, you need to use dateTimeLabelFormats under y axis as below

            type: 'datetime',

            dateTimeLabelFormats: {
            millisecond: '%H:%M:%S',
            second: '%H:%M:%S',
            minute: '%H:%M:%S',
            hour: '%H:%M:%S'
            },

To get your tooltip aligned with H:M:S format, add this

            tooltip: {
                    enabled: true,
                    formatter: function() {
                      var main = '<b>'+ Highcharts.dateFormat('%A, %b %e, %Y', this.x) +'</b>';
                      s = Math.floor(this.y / 1000);
                      m = Math.floor(s / 60);
                      s = s % 60;
                      h = Math.floor(m / 60);
                      m = m % 60;
                      h = h % 24;
                      if (h < 9) h = "0" + h;
                      if (m < 9) m = "0" + m;
                      if (s < 9) s = "0" + s;
                      return '<b>'+ this.x +'</b><br>' + '<span style="color:green">Value-</span>' + [h, m, s].join(':');
                    }
            },

Hope this helps for the newbies like me :)

Upvotes: 0

Views: 1185

Answers (1)

Amadan
Amadan

Reputation: 198334

As I said in comments, convert series into seconds:

var hms = val.split(':');
var secs = hms[0] * 3600 + hms[1] * 60 + hms[2];
series.push(secs);

Then set the yAxis.formatter to this function to restore the H:M:S on the axis:

function() {
  var h = Math.floor(this.value / 3600);
  var m = Math.floor(this.value / 60) % 60;
  var s = this.value % 60;
  if (h < 9) h = "0" + h;
  if (m < 9) m = "0" + m;
  if (s < 9) s = "0" + s;
  return [h, m, s].join(':');
}

Messing about with datetime is counterproductive, since it is never meant to hold dateless time.

(Disclaimer: all this deduced from the API description, I have no familiarity with Highchart.)

Upvotes: 1

Related Questions