0

TL;DR: How would I convert the string "1.619820361123853E9" to a Date in JavaScript?


Long story: The TIMESTAMP values from BigQuery.Jobs.query() in Google Apps Script come back as big numbers within a string. For example:

SELECT CURRENT_TIMESTAMP() AS today_timestamp

Running this in a Google Apps Script project (using code from https://developers.google.com/apps-script/advanced/bigquery as a guide) looks someting like this:

  const request = {
    query: "SELECT CURRENT_TIMESTAMP() AS today_timestamp",
    useLegacySql: false
  };
  let queryResults = BigQuery.Jobs.query(request, DW_PROJECT_ID);
  let jobId = queryResults.jobReference.jobId;

  let sleepTimeMs = 500;
  while (!queryResults.jobComplete) {
    Logger.log(`Waiting for query: $jobId ($sleepTimeMs)`);
    Utilities.sleep(sleepTimeMs);
    sleepTimeMs *= 2;
    queryResults = BigQuery.Jobs.getQueryResults(DW_PROJECT_ID, jobId);
  }

  let rows = queryResults.rows;
  while (queryResults.pageToken) {
    queryResults = BigQuery.Jobs.getQueryResults(DW_PROJECT_ID, jobId, {
      pageToken: queryResults.pageToken
    });
    rows = rows.concat(queryResults.rows);
  }

  let data = new Array(rows.length);
  for (let i = 0; i < rows.length; i++) {
    let cols = rows[i].f;
    data[i] = new Array(cols.length);
    for (let j = 0; j < cols.length; j++) {
      data[i][j] = cols[j].v;
    }
  }

  Logger.log(`BQ to JavaScript TIMESTAMP: ${data[0][0]}`)

The result is that data[0][0] is something like "1.619820361123853E9" (a string).

How would I convert this to a Date?

Neil C. Obremski
  • 18,696
  • 24
  • 83
  • 112
  • It looks like at Date() value so try new Date(value); [ref](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date) – Cooper Apr 30 '21 at 22:29
  • Trying `new Date(parseFloat("1.619820361123853E9"))` gives me Mon Jan 19 1970 09:57:00 GMT-0800 (Pacific Standard Time) ... that's not right! :) – Neil C. Obremski Apr 30 '21 at 22:33
  • Ah ha! `new Date(Number("1.619820361123853E9") * 1000)` ... thanks to https://stackoverflow.com/questions/10943997/how-to-convert-a-string-containing-scientific-notation-to-correct-javascript-num – Neil C. Obremski Apr 30 '21 at 22:45

1 Answers1

1

In order to convert the string to a date, you should try this:

new Date(Number("1.619820361123853E9") * 1000)
ale13
  • 5,679
  • 3
  • 10
  • 25