This will be a short one. Just wanted to point out a nice library for NodeJS I found recently.

Lately I have been working on exporting part of our data as a CSV for easier reading and interpreting by non-programmers. Part of the export process was converting time stamps to formatted dates. Usually this isn’t a problem in Javascript since you can just use theĀ Date object.

var timestamp = 8172837178; 

var date = new Date(timestamp); 

console.log(date.toString());

This will print a human readable string for a time stamp.

One problem with this approach is that the time stamp will be converted according to the timezone of the computer doing the converting. So if your computer’s timezone is set to Europe/Amsterdam you will see the time as it is in Amsterdam.

This can be problematic if you are formatting the time stamps on a server and the client viewing the data does so in a different timezone. For example your server’s timezone is Europe/Amsterdam and the client is located in New York. The times shown in the CSV might not make a lot of sense if the user is not aware of this! Ideally the time stamps are converted using the timezone of the client, not the timezone of the server.

Sadly Javascript (and by extension NodeJS) do not support this. So we have to find (or program) an alternative.

A quick search yielded a solution: timezone!

With timezone you can format dates for any timezone based on the timezone identifier (“Europe/Amsterdam”, “America/New_York”, etc.). This was exactly what I needed since any customer can now just pass along his/her timezone!

Installing timezone for NodeJS is easy:

$ npm install moment-timezone

Using the above example you can convert any time stamp to the time as it was in, say, New York:

var moment = require("moment-timezone");

var timestamp = 8172837178; 

var date = moment.tz(timestamp, "America/New_York");

console.log(date.format()); // Tada! Formatted date for New York!

That’s it, easy converting of time stamps for any timezone!