The Simplest Way Of Check If A Data Type Of An Element In An Array Is A Date Object?
I want to create a condition that checks if a data type of an element in an array (formed by data from a spreadsheet) is a date object (so, I can manipulate the string format of th
Solution 1:
You can use the instanceof
keyword.
if (data[i] instanceof Date) {
//it's a date
} else {
//it's not
}
To format the date, you can do it like:
var d = new Date(), //date from data[i]
m = d.getMonth() + 1, //months starts at 0
y = d.getFullYear(),
d = d.getDate();
console.log([d, m, y].join('/'));
Solution 2:
Don't forget GAS has a dedicated method to format dates:
Utilities.format date(date,TZ,string representation);
You can use it to customize the way you show dates.
This approach has a few advantages over the string manipulation suggested in the other answer :
- it takes the time zone into account
- it can use richer formats (like month in text format)
- it's shorter to write ;-)
Here is an example function to illustrate (read comments in code, I took the time zone parameter in the spreadsheet itself so we're sure that no error can come from this parameter)
function convertDatesToStrings(){
var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var data = ss.getDataRange().getValues();
for(n=0 ; n<data.length;++n){
var row = data[n];
for(var i=0; i<row.length; i++) {
if (row[i] instanceof Date) {
data[n][i] = "'"+Utilities.formatDate(row[i], SpreadsheetApp.getActiveSpreadsheet().getSpreadsheetTimeZone(), "dd/MM/yy");// is a string
// added a ' before the string to ensure the spreadsheet won't convert it back automatically
Logger.log('Array cell '+n+','+i+' modified to '+data[n][i])
}
}
}
ss.getRange(1,1,data.length,data[0].length).setValues(data);// write back to sheet
}
Solution 3:
Here's a simple custom date validation function:
function isDate(date) {
return (date.constructor.name == 'Date');
}
Post a Comment for "The Simplest Way Of Check If A Data Type Of An Element In An Array Is A Date Object?"