I have a google spreadsheet in which I need to check if the value entered in the cell by the user is a date, if it is a date, it must be formatted as dd/MM/yy
, if it is not a date, than the value must be converted to uppercase.
The date conversion is what is not working by now, and i would like some help on how can i do that.
This is how the script is right now. Thanks in advance.
function onEdit(e) {
var tab = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getName();
if (tab != "backup") { //this is NOT working
if(isDate(e.range.getValue())) {
var date = new Date(e.range.getValue());
var formattedDate = Utilities.formatDate(date, "GMT-3", 'dd/MM/yy');
e.range.setValue(formattedDate);
} else { //this is working
e.range.setValue(e.value.toUpperCase());
}
}
}
function isDate(date) {
return(Object.prototype.toString.call(date) === '[object Date]');
}
EDIT: the simplest solution i found for this is:
function onEdit(e) {
var tab = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getName();
if (tab != "backup") {
if(isDate(e.range.getValue())) {
e.range.setNumberFormat("dd/MM/yy");
} else {
e.range.setValue(e.value.toUpperCase());
}
}
}
function isDate(date) {
return(Object.prototype.toString.call(date) === '[object Date]');
}
I am not fully familiar with your data and/or error you are encountering but how about this alternative solution:
function onEdit(e) {
var tab = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getName();
if (tab != "backup") {
if(isDate(e.range.getValue())) {
var date = new Date(e.range.getValue());
var formattedDate = Utilities.formatDate(date, "GMT-3", "''dd/MM/yy"); // using '' to force string literal
e.range.setValue(formattedDate);
} else { //this is working
e.range.setValue(e.value.toUpperCase());
}
}
}
function isDate(date) {
return(Object.prototype.toString.call(date) === '[object Date]');
}
You can use this symbol ''
to force the format of date to your desired output.
Result:
Ref: Google Apps Script date format issue (Utilities.formatDate)