1

Hey i have a scrip that takes data for sheest and populates a gdoc file one of the lines is a date

const friendlyDate = new Date(row[2]).toLocaleDateString();

but if there is not entered a date in the cell it returns "Invbalid Date" to the Gdoc file how whould i go about adding a if satement to check if there is a valid date in the cell and if not make the output text "Not registered on date"

I did try different if combinations but i am not that skilled in appscript

æHandal
  • 21
  • 1

2 Answers2

1

From Invbalid Date, I thought that row[2] might be "". If my understanding is correct, although, unfortunately, I cannot know your whole script, how about the following modification?

Pattern 1:

const friendlyDate = row[2] && new Date(row[2]).toLocaleDateString();
  • In this pattern, when row[2] is "", friendlyDate is "".

Pattern 2:

This is from this thread.

const date = new Date(row[2]);
const friendlyDate = isNaN(date.getTime()) ? row[2] : date.toLocaleDateString();
  • In this pattern, when !isNaN(date.getTime()) is true, friendlyDate is the value of date.toLocaleDateString(). And, when !isNaN(date.getTime()) is false, friendlyDate is "".

Note:

  • When the value of row[2] is an invalid value for new Date(), if you want to return another value, please modify the above script.
Tanaike
  • 181,128
  • 11
  • 97
  • 165
1

You can try this.

function test() {
  try {
    getDate( new Date() );
    getDate( 1 );
    getDate( "hello" ); 
  }
  catch(err) {
    console.log("Error in test: "+err);
  }
}

function getDate(value) {
  try {
    if( value.constructor.name === "Date" ) {
      console.log(value.toLocaleDateString());
    }
    else {
      console.log("not a date")
    }
  }
  catch(err) {
    console.log("Error in doStuff: "+err);
  }
}

4:54:05 AM  Notice  Execution started
4:54:09 AM  Info    11/1/2022
4:54:09 AM  Info    not a date
4:54:09 AM  Info    not a date
4:54:06 AM  Notice  Execution completed
TheWizEd
  • 7,517
  • 2
  • 11
  • 19