Reputation: 39
I want to compare two dates and make something if they are equal.
The first date come from a google sheet. The cell format is a date and the localization is at France (GMT+1). The second date come from an HTML form date field filled by the user.
I want to compare the strings in the yyyy--MM--dd format, so I used the function Utilities.format(). When I display the string values, everything seems to be okay.
But when the string comparison doesn't work. It's probably a conversion issue. I did some tests, nothin works.
Here's a part of my code
//...
} else {
SpreadsheetApp.getUi().alert(formObject.licenseExpiration); // Works. Displays yyyy-MM--dd
SpreadsheetApp.getUi().alert(Utilities.formatDate(sheetDataRangeValues[0][7], "GMT+1", "yyyy-MM-dd")); // Works. Displays yyyy-MM--dd
if (Utilities.formatDate(formObject.licenseExpiration, "GMT+1", "yyyy-MM-dd") == Utilities.formatDate(sheetDataRangeValues[0][7], "GMT+1", "yyyy-MM-dd") || formObject.licenseExpiration == "") {
SpreadsheetApp.getUi().alert("It works !");
}
//...
Thanks for your help.
Edit:
HTML
<form id="filterForm" onSubmit="handleFormSubmitFilter(this)">
<label for="licenseExpiration">License Expiration</label><br/>
<input type="date" id="licenseExpiration" name="licenseExpiration"><br/><br/>
</form>
<script>
function preventFormSubmitFilter() {
var formsFilter = document.querySelectorAll('FormFilter');
for (var i; i < formsFilter.length; i++) {
formsFilter[i].addEventListener('submit', function(event) {
event.preventDefault();
});
}
}
window.addEventListener('load', preventFormSubmitFilter);
function handleFormSubmitFilter(formObject) {
google.script.run.processFormFilter(formObject);
document.getElementById("filterForm").reset();
}
</script>
Upvotes: 0
Views: 132
Reputation: 1610
For the best result you need pass the "raw" date in a new Date object. Then use the Utilities to convert this to a string. Tip: use console.log() to (or better, the debugger) see your output.
const licenseDate = Utilities.formatDate(new Date(formObject.licenseExpiration), Session.getScriptTimeZone(), "yyyy-MM-dd");
const sheetDate = Utilities.formatDate(new Date(sheetDataRangeValues[0][7]), Session.getScriptTimeZone(), "yyyy-MM-DD");
if (sheetDate == licenseDate || formObject.licenseExpiration == "") {
console.log('it works')
}
Upvotes: 1