Jan Peters
Jan Peters

Reputation: 13

Problem converting Strings into dates in a multidimensional array in javascript (GAS)

In order to automate some daily processes I am reading data from a google sheet and putting them into a dictionary. From said dictionary the data is then written into other sheets. It all works like a charm apart from one little bug that I do not understand:

I get all the data from the sheet and put it into a dictionary like so:

  var data = sheetImp.getRange(1,1, sheetImp.getLastRow(), sheetImp.getLastColumn()).getValues();
  var bib_tis = {};
  for (var i = 0; i < data.length; i++) {
    var date = new Date(data[i][0]);
    date.setHours(0, 0, 0, 0);
    if (date.valueOf() == yesterday.valueOf()) {
      var key = data[i][4] + ' ' + data[i][2]
      bib_tis[key.trim()] = data[i][5];    
    }
  }

I check if date is yesterday because I only need that data. The dictionary contains all lines but the very first one. To check that I did the following in order to debug:

  Logger.log(typeof(data[0][0]));    // string
  Logger.log(data[0][0].valueOf());  // 2019-11-12T00:00:00+01:00
  Logger.log(data[0][0]);            // 2019-11-12T00:00:00+01:00
  Logger.log(new Date(data[0][0]));  // Thu Jan 01 01:00:00 GMT+01:00 1970
  Logger.log(typeof(data[1][0]));    // string
  Logger.log(data[1][0].valueOf());  // 2019-11-12T00:00:00+01:00
  Logger.log(data[1][0]);            // 2019-11-12T00:00:00+01:00
  Logger.log(new Date(data[1][0]));  // Tue Nov 12 00:00:00 GMT+01:00 2019

Why does the first date not convert correctly?

I could try to work the other way around and convert yesterday to a string and compare strings but I do not understand why this doesn't work for the first line in the array?

Kind regards Jan

Upvotes: 1

Views: 37

Answers (1)

Michael Beeson
Michael Beeson

Reputation: 2875

You have fallen foul of an invisible utf character: U+FEFF

Try copying the output of your logs, and paste them into a hidden character revealer, for example:

https://www.soscisurvey.de/tools/view-chars.php

You'll see that for the first date you have U+FEFF at the start of the date (but not for the second date).

Here's a blog about that character, aka ZERO WIDTH NO-BREAK SPACE:

https://www.freecodecamp.org/news/a-quick-tale-about-feff-the-invisible-character-cd25cd4630e7/

Now you can try stripping that character away, or look into why it's being prepended to that date. It has something to do with utf16 encoding.

Good luck!

Upvotes: 1

Related Questions