O
O
OpenReligion2019-02-25 09:18:26
Google Apps Script
OpenReligion, 2019-02-25 09:18:26

How to understand that the entered value is a date?

There is a cell in the Google Sheet where users enter the date of birth of customers.
In 95% of cases, they record either February 25, or February 25 or February 25, 1980.
Through Google Script, I then transfer the entered value to another table and set a single format along the way

var birthday1 = ss1.getRange("D8").getValue();
var birthday = Utilities.formatDate(birthday1, "GMT+3", "dd-MM-yyyy")

Problems begin if the user leaves the cell empty or enters a date that is not there, for example, the phrase: "I don't know."
Then, when executing the Utilities.formatDate script, it gives an error.
Is it possible to use a short code to understand if the entered value is a date, and only then apply Utilities.formatDate to it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Ivanov, 2019-02-25
@OpenReligion

The question is more for JavaScript, not for Google Apps Script.
Check for the presence of something in a variable, and then check if that variable has a getTime.

function isDate(value){
  return value && value.getTime;
}

An academic way that didn't work in scripts before because something was missing.
function isDate(date){
  return date instanceof Date && !isNaN(date.valueOf());
}

Solution
Example with undefined result without throwing an error
var birthday1 = ss1.getRange("D8").getValue();
var birthday = isDate(birthday1) ?
  Utilities.formatDate(birthday1, "GMT+3", "dd-MM-yyyy") : 
  undefined;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question