What format does the highcharts js library accept for dates?

后端 未结 2 1833
-上瘾入骨i
-上瘾入骨i 2020-12-08 19:10

I am using highcharts and cannot figure out what the date input should be from rails dates to the highcharts accepted format for dates.

In my migration file i am sto

相关标签:
2条回答
  • 2020-12-08 19:52

    Internally Highcharts uses javascript Date numbers (the number of milliseconds since Jan 1st 1970) to represent dates. See Mozilla reference.

    To get dates on an axis you will first need to set the axis type to 'datetime':

    xAxis: {
        type: 'datetime'
    }
    

    You have a few options when specifying the series data (all three examples produce the same chart):

    1. Setting a start point and using a fixed interval between points

      pointStart: Date.UTC(2012, 2, 6, 10),
      pointInterval: 1000 * 60 * 60,
      data: [5, 6, 4]
      
    2. Specifying the exact date using the Date.UTC method. This way its readable for humans:

      data: [
          [Date.UTC(2012, 2, 6, 10), 5], 
          [Date.UTC(2012, 2, 6, 11), 6], 
          [Date.UTC(2012, 2, 6, 12), 4]]
      
    3. Or specifying the epoch time directly:

      [[1331028000000, 5], [1331031600000, 6], [1331035200000, 4]]
      

    Example on jsfiddle

    0 讨论(0)
  • 2020-12-08 19:54

    Adding to @eolsson, epoch time is usually the way to go since technically, Date() objects are javascript, not JSON, and you're unlikely to find an off-the-shelf serializer that generates them.

    You'll want to format the date, too, something like this --

    xAxis: {
      type: 'datetime',
      labels: {
        formatter: function() {
          return Highcharts.dateFormat('%e %b', this.value*1000); // milliseconds not seconds
        },
      }
    }
    

    The date formatting is done php style.

    0 讨论(0)
提交回复
热议问题