Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Javascript convert UTC date to a different timezone using moment.timezone.js and d3.js
var dateFormat = d3.time.format("%m/%d/%Y %H:%M:%S");
function dateConversion(utcTimestamp) {
//it took me nearly an entire day to write this one stupid line of code because js dates => teh suck
//the date from the file comes in as UTC (below)
//UTC: 1/7/2015 10:49:07 PM
//these are the equivilient
//America/Chicago: 1/7/2015 4:49:07 PM
//America/Los_Angeles: 1/7/2015 2:49:07 PM
//the problem resides in that moment js can keep track of timezones fairly well, but stay away from its "toDate" function
//as it ALWAYS converts it to the local machine timezone. JS has NO WAY of keeping data in a different timezone. If
//d3's axis component used moment instead of native datetime, we probably wouldn't have had the issue
//it is probable that we could have done this using just moment.js and not involve d3, but I was just happy to have something that worked.
//there may be a more efficient way of doing this, but after trying a gajillion iterations, leave the magic code alone
//Ultimately, if fed the above utc date and our timezone is America/Los_Angeles, we need to return "1/7/2015 2:49:07 PM" *AS A JAVASCRIPT DATE*
//If you're in eastern time, when you show the date in the console, it'll say "1/7/2015 14:49:07 GMT-0500". That is ok. Ignore timezone
//on javascript dates. Ultimately what matters is that the graph will show 2:49 PM as that was the local time for that project.
//thankfully when we are displaying the dates, it is via d3 and we can make sure that the GMT-0500 doesn't show
return dateFormat.parse(moment(utcTimestamp + "+0000").tz(_timezone).format("MM/DD/YYYY HH:mm:ss"))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.