1

First of all, there is a similar question here and I also read GitHub issues related to xFormat & timestamp (i.e. here). None of these solved my problem.

From D3 Time Format :

%Q - milliseconds since UNIX epoch.
%s - seconds since UNIX epoch.

When using xFormat: '%Q' and timestamp in milliseconds (i.e. 1524362421000), it is working.

But when using xFormat: '%s' and timestamp in seconds (i.e. 1524362421) all tick marks along x-axis showing wrong date: 1970-01-18)

axis: {
    x: {
      type: 'timeseries',
      tick: {
          fit: true,
          format: "%Y-%m-%d",
          rotate: 45
     }
}

Here is the JS Fiddle

The JSON response from API uses timestamp in seconds and I can not change it to milliseconds (I know JS uses milliseconds to parse date). Therefore, I need xFormat: '%s' to work.

MD TAREQ HASSAN
  • 1,188
  • 20
  • 46

1 Answers1

1

Actually whats going on with your code is that xFormat is not doing anything with your format strings - it formats directly the strings when you're not using the tick formatter. You can remove it and it will still work with millis because its the "type":"timeseries" argument from tick that is doing all the magic. But, as you said, we can work on a solution with a d3.js time formatter. As a solution, you could replace your xAxisSettings with this:

var xAxisSetting = {
  //type: 'timeseries',
  tick: {
    fit: true,
    format:function (x) {
        var formatSeconds = d3.time.format("%Y-%m-%d")
        return formatSeconds(new Date(x*1000)); },
    count: 8,
    rotate: 45
  },
  label: {
    text: 'Date',
    position: 'outer-center'
  },
  //min: xMin,
  //max: xMax,
  padding: {
    left: 0,
    right: 0
  },
  height: 70
};

What we did here:

  • We commented out the type timeseries as we are doing our own time formatting (don't forget to import d3-time and d3-time-format to your project). If you don't remove this line, it will format as a date and it will not remain as a timestamp for us to do our own formatting stuff.
  • The format now has a function where the argument x is the seconds string that is coming from your json object. We are simply writting the d3 simple seconds formatter inside the function.
  • The formatter needs a date as a parameter, so we create one as pass the milliseconds (seconds * 1000)

You can see it working here. Hope it meets your expectations.

brunags
  • 292
  • 2
  • 7