Question

I'm using Google Scripts for some Google Spreadsheets magic and the automatic date parsing is driving me nuts! The sheet I'm working with is littered with all sorts of date formats and I would much rather deal with them as Strings, than have Google convert them to Date objects with each .getValues() call. After much searching, I still cannot find a way to stop/disable Google from automatically parsing these Strings. Does anyone know how?

Was it helpful?

Solution

Yes it is possible, but you must make a change before calling getValues, and use getDisplayValues():

  // do not use getValues(), which will convert dates
  var string_data = my_sheet.getRange(...).getDisplayValues();

If you only want to use the display value in the limited case of, say, dates, you can copy both values and displays, then test whether your value is a date, and if it is, use the corresponding display instead:

  // use getDisplayValues() for dates, getValues() otherwise
  var string_data = my_sheet.getRange(...).getDisplayValues();
  var value_data =  my_sheet.getRange(...).getValues();

  value_data.forEach(function(row_vals, i) {
    row.forEach(function(cell_val, j) {
      if(is_date(cell_val)) // see e.g. https://stackoverflow.com/a/17110249/3160967
        do_something_with(string_data(i, j));
      else
        do_something_with(cell_val);
    });
  });

Lastly, the above needs modification if you want to use it as a sheet function, because function calls automatically apply getValues() before the function code is executed. To get around this, you can use the techniques described at https://webapps.stackexchange.com/a/30784

OTHER TIPS

It's indeed not possible, but a feasible workaround is to create an auxiliary sheet and insert a formula to concatenate all values on the source sheet with an empty string. Then getValues() on this auxiliary sheet, which may be hidden or removed by the script after used.

The formula can be as simple as setting this on A1 of the auxiliar sheet

=ArrayFormula(Sheet1!A:T&"")

A caveat with this workaround is that if the user set a custom formatting for his dates, they will not be kept. But if that's important you can get them by using getNumberFormats()

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top