My server side model is saving date/time in UTC. In my front end I am using moment.js to create time objects using the server side data.
However, I am using d3 to plot the data and I am not quite sure how I can initialize d3.scale.utc() using my moment object. I need to render the axis scale in UTC time.
Previously, d3.scale.utc().domain(starDate, endDate) was working where startDate and endDate were native JavaScript date objects.
But now that I have refactored the code to use moment.js to handle UTC time and making some of the date and time manipulation functions simplified, I am facing this plotting issue.
You have a moment object and you want to feed it to d3? Easiest way is to just use JavaScript epoch times obtained via valueOf():
var startDate = moment().subtract(10, 'hours').utc();
var endDate = moment().add(10, 'hours').utc();
var x = d3.time.scale.utc()
.domain([startDate.valueOf(), endDate.valueOf()])
.range([0, 400]);
var xAxis = d3.svg.axis()
.scale(x);
var svg = d3.select("body").append("svg")
.attr("width", 410)
.attr("height", 210)
.append("g")
.attr("transform", "translate(" + 10 + "," + 10+ ")");
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + 0 + ")")
.call(xAxis)
.selectAll("text")
.attr("y", 0)
.attr("x", 9)
.attr("dy", ".35em")
.attr("transform", "rotate(90)")
.style("text-anchor", "start");
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.11.1/moment.js"></script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With