G to the Square

Timestamp formatting and JSON to CSV JavaScript Utils


These are a couple of utils that once in while I need , but I'm too lazy to think about how to write it from scratch. So, I end up searching for on the internet hoping to end on the correct Stack Overflow answer.

Then I realized that the best thing to do is to blog such things on my blog.

Formatting UNIX timestamp (in milliseconds)

Please note that UNIX timestamp is in seconds. However, the Date() constructor expects it in milliseconds. Apparently this is called ECMASCRIPT epoch, so you will need to multiply it by 1000.

Based on MDNs documentation about the Date constructor:

An integer value representing the number of milliseconds since January 1, 1970, 00:00:00 UTC (the ECMAScript epoch, equivalent to the UNIX epoch), with leap seconds ignored. Keep in mind that most UNIX Timestamp functions are only accurate to the nearest second.

Also, seems that by design javascript uses milliseconds

 * Pass a timestamp and returns a string with format YYYY-MM-DD HH:MM:SS
 * @param ts {number} UNIX timestamp in milliseconds
 * @returns {string} YYYY-MM-DD HH:MM:SS
function timestampToFormattedDateTime(ts) {
  const d = new Date(ts);
  // expected toISOString output 2011-10-05T14:48:00.000Z. We extract just the date.
  const date = d.toISOString().split('T')[0];
  // expected toTimeString output 23:15:30 GMT+0200 (CEST).
  // We generate a time that takes into account the timezone given in the date
  const time = d.toTimeString().split(' ')[0];
  return `${date} ${time}`;

Array of objects to CSV format

The function below returns a string. So, if you need to save it to a file you will need to use node.js for it.

Finally, note that this can be done in a way where you concatenate using a variable. I'm a big fan of coding Javascript in functional form. The main reason is that it gives you hints of when you should separate functions in two, it is like a small puzzle and models functions as inputs and outputs, which leads to programs that are easier to test and maintain.

 * In with an array of objects (generally taken from an API that returns a JSON Data array)
 * e.g. [{ email: 'my@example.com', name: 'MY Example', role: 'admin'}, ...]
 * @param objArr {Array<Object>}
 * @returns {* | string} Multiline string repressing a Comma seperated values file content.
 * To be used to generating Excel or similar sheets and workbooks with the content.
 * e.g.
 * email,name,role
 * my@example.com,MY Example,admin
function objArrayToCSV(objArr) {
  const header = `${Object.keys(objArr[0]).join(',')}\n`;

  return objArr.reduce((acc, objRow) => {
    const row = `${Object.values(objRow).join(',')}\n`;
    return `${acc}${row}`;
  }, header);
Geries Handal Profile picture

Occasionally, I write my opinions on software development. By Geries Handal. Github, Gitlab

Copyright © 2022 Geries Handal