SQL date discrepancy with some dates - javascript

I am working on a date problem.
So, in the app I have a table that have some user records that includes a date of birth field (datetime sql type). The problem is that for some users whose date of birth is prior to 1954, the date is not properly reflected.
For example, I have a user whose date of birth is 11/08/1920 but when I set the date of birth via server script, it ends up with the value 11/07/1920 23:23:24.
I am getting the date value from a spreadsheet and the server script looks like this:
function importDOBs(){
var allRecs = [];
var ss = SpreadsheetApp.openById("adfsasdfasdfasdfasdfasdf");
var sheet = ss.getActiveSheet();
var data = sheet.getRange(2,4,sheet.getLastRow(),2).getValues();
for(var i=0; i<5; i++){
var row = data[i];
var date = row[0];
var oldMrn = row[1];
var query = app.models.purgedRecords.newQuery();
query.filters.oldMrn._equals = oldMrn;
var record = query.run()[0];
if(record){
var dob = new Date(date);
record.dateOfBirth = dob;
allRecs.push(record);
}
}
app.saveRecords(allRecs);
}
These are the values in the spreadsheet (they are strings, not dates):
1954-03-04T00:00:00
2014-03-01T00:00:00
1951-10-20T00:00:00
1920-11-08T00:00:00
1938-09-27T00:00:00
However, somehow I'm always getting this:
As you see, there is a discrepancy on the dates that are prior to 1954. So far, I have tried other things such as changing this part:
if(record){
var dob = new Date(date);
record.dateOfBirth = dob;
allRecs.push(record);
}
to this:
if(record){
var dob = Utilities.formatDate(new Date(date),"GMT","yyyy-MM-dd'T'HH:mm:ss'Z'");
var birthDate = new Date(dob);
record.dateOfBirth = birthDate;
allRecs.push(record);
}
and the above resulted in the same thing. I have tried other dates after 1954 and they also seem wrong. For example 05/19/1968 reflects 05/18/1968 23:00:00. So my best guess so far this has to do something with the daylight savings, perhaps?

The snake pit of converting dates between platforms
Try to set the values to UTC or just format them into the datetime format for MySQL
The first option as seen in the snippet below requires you to convert the format in SQL:
See this answer: MySQL yyyy-mm-ddThh:mm:ss.sssZ to yyyy-mm-dd hh:mm:ss
DATE_FORMAT(STR_TO_DATE(«string»,'%Y-%m-%dT%H:%i:%s.000Z'),'%Y-%m-%d %H:%i:%s');
//Using Z to set to UTC
let allRecs = [];
document.querySelector("pre").textContent.split("\n").forEach(function(element) {
if (element != "") {
const dob = new Date(element + "Z"); //Z forces te date to be in UTC with zero time offzet or: 00:00:00
const dateOfBirth = dob;
allRecs.push(dateOfBirth);
}
});
console.log(allRecs);
allRecs = [];
//format to MySQL datetime format
document.querySelector("pre").textContent.split("\n").forEach(function(element) {
if (element != "") {
element = element.replace("T", " "); //replace T with space
//now the string is in the datetime format for MySQL
allRecs.push(element);
}
});
console.log(allRecs);
<pre>
1954-03-04T00:00:00
2014-03-01T00:00:00
1951-10-20T00:00:00
1920-11-08T00:00:00
1938-09-27T00:00:00
</pre>

Related

My code just decided to stop working and I don't know why. (javascript google appscript)

Thanks in advance to anyone who can help with my issue. I'm not a professionnal I just code when I don't want to do a task anymore.
So I'm running a script to send automaticaly emails 3 days after I see a client. Two days ago, I see that my emails are not been sent at the correct date. So I enter different date to see what's the problem is and the code just send reply for any given date in my google sheet. All date but the 31/05/2022 for some reason.
So I just waited a couple of days to fix it and when I came back the code just stop working completely. Meaning it doesn't send any email anymore.
I'm using the following code with a time trigger and I dont see why it doesnt work anymore.
function MailingAutoJuillet() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Juillet");
var startRow = 3;
var numRows = sheet.getLastRow()-1;
var dataRange = sheet.getRange(startRow, 1, numRows, sheet.getLastColumn());
var data = dataRange.getValues();
var EMAIL_SENT = 'EMAIL_SENT';
var NO_EMAIL = 'NO_EMAIL';
for (var i = 0; i < data.length; ++i) {
var row = data[i];
var date = new Date();
var sheetDate = new Date(row[2]);
Sdate = Utilities.formatDate(date,'Europe/Paris','EEE, MMM d, yyyy')
SsheetDate = Utilities.formatDate(sheetDate,'Europe/Paris','EEE, MMM d, yyyy')
if (Sdate >= SsheetDate+3){
if (row[13] != EMAIL_SENT)
if (row[13] != NO_EMAIL) {
const HTMLTemplate = HtmlService.createTemplateFromFile("HTML Mail de rappel")
const HTMLforemail = HTMLTemplate.evaluate().getContent()
var emailAddress = row[9];
var emailText = "Text";
var subject = "Text";
var option={
htmlBody:HTMLforemail
};
GmailApp.sendEmail(emailAddress,subject,emailText,option);
sheet.getRange(startRow+i,14).setValue("EMAIL_SENT");
}
}
}
}
Attempting to use greater than operator to compare strings
You cannot compare dates in this manner
Sdate = Utilities.formatDate(date,'Europe/Paris','EEE, MMM d, yyyy')
SsheetDate = Utilities.formatDate(sheetDate,'Europe/Paris','EEE, MMM d, yyyy')
The above are strings and cannot be compared with greater than operators
if (Sdate >= SsheetDate+3){
Take a look at the getTime() or valueOf() methods that return milliseconds which can be compared in the manner that you wish.
use the function Logger.log() to know what exactly you code are doing.
Since you don't have any clue I would recommend starting knowing the values of each variable:
Logger.log("varname=",varname);
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Juillet");
ex: Logger.log("sheet=",sheet);
Also, I don't know how exactly is your sheet, but let my try to understand what is happening here:
var sheetDate = new Date(row[2]); //row is expected to be an array
but
var row = data[i]; so... row receive here the values in data? It's data an 2d array?
Also, check your executions. It's the fourth icon on the left panel in the new IDE
You can't compare dates that way.
SsheetDate = Utilities.formatDate(sheetDate,'Europe/Paris','EEE, MMM d, yyyy')
...is going to produce a string value, like "Tue, Jun 7, 2022". You can't add the number three to that to get a date three days later. All you'll be doing is comparing something like "Tue, Jun 7, 2022" to "Tue, Jun 7, 20223", and they will compare as strings, not as dates or numbers.
A day is 86,400,000 milliseconds. When Sdate is three or more days after SsheetDate, Sdate.getTime() > SsheetDate.getTime() + 259200000.
There are more elegant, easier-to-read ways to compare dates, but those methods are more complicated and/or depend on particular date/time libraries.

How to compare dates to make sure Google Apps Script is only sending an alert once a day?

I have a script in a Google Sheet that is sending out an alert if a certain condition is met. I want to trigger the script to run hourly, however, if an alert was already sent out today, I don't want to send out another one (only the next day). What is the best way to achieve this?
I've tried formatting the date several ways, but somehow the only thing working for me so far is getting the year, month and day from the date object as int and comparing them separately.
function sendAlert{
var now = new Date();
var yearNow = now.getYear();
var monthNow = now.getMonth() + 1;
var dayNow = now.getDate();
var sheet = SpreadsheetApp.getActive().getSheetByName('CHANGE_ALERT');
var sentYear = sheet.getRange("R2").getValue();
var sentMonth = sheet.getRange("S2").getValue();
var sentDay = sheet.getRange("T2").getValue();
if (yearNow != sentYear || monthNow != sentMonth || dayNow != sentDay) {
sendEmail();
var sentYear = sheet.getRange("R2").setValue(yearNow);
var sentMonth = sheet.getRange("S2").setValue(monthNow);
var sentDay = sheet.getRange("T2").setValue(dayNow);
else {
Logger.log('Alert was already sent today.');
}
}
I think this solution is definitely not the best approach, but I cannot come up with another that merges the date into one. Only comparing the new Date() doesn't work, since the time of day will not necessarily be the same. If I format the date to YYYY-MM-dd, it should work, but then when I get the date again from the spreadsheet it gets it as a full date with the time again.
Requirement:
Compare dates and send an email if one hasn't been sent already today.
Modified Code:
function sendAlert() {
var sheet = SpreadsheetApp.getActive().getSheetByName('blank');
var cell = sheet.getRange(2,18); //cell R2
var date = new Date();
var alertDate = Utilities.formatDate(cell.getValue(), "GMT+0", "yyyy-MM-dd");
var currentDate = Utilities.formatDate(date, "GMT+0", "yyyy-MM-dd");
if (alertDate !== currentDate) {
sendEmail();
cell.setValue(date);
} else {
Logger.log('Alert was already sent today.');
}
}
As you can see, I've removed all of your year/month/day code and replaced it with Utilities.formatDate(), this allows you to compare the dates in the format you specified in your question. I've also changed the if statement to match this, so now we only need to compare alertDate and currentDate.
References:
Utilities.formatDate()
Class SimpleDateFormat

Insert wrong date in MongoDB

I am tring to save dates in my MongoDB table using C#.
Here is a JavaScript logic that send data using Ajax to C# controller
$(function ($, w, d) {
var _user = {}
//var time = moment("2016-04-02", "YYYYMMDD").fromNow()
//var bime = moment().endOf('day').fromNow();
//var crime = moment("20120620", "YYYYMMDD").fromNow();
// document.getElementById('time').innerHTML = time;
var obj = {};
var holidaylist = ["Mar-31-2018", "Apr-01-2018","Apr-04-2018","Apr-07-2018","Apr-08-2018"];
var startdate = new Date("Apr-02-2018");
obj.endDate = "Apr-06-2018";
obj.holidaylist = holidaylist;
obj.NumberOfCount = 9;
CallAjax("POST", '/LeaveManagement/', 'checkleavelogic', obj, onsuccessaddemployee, '');
here is the C# logic that saves the data in MongoDB:
public JsonResult checkLeaveLogic(LeaveLogicModel leaveLogic)
{
string strconnectiomstring = "mongodb://10.10.32.125:27017";
MongoClient Client = new MongoClient(strconnectiomstring);
var DB = Client.GetDatabase("TimeClock");
List<DateTime> leavesDate = new List<DateTime>();
var collection = DB.GetCollection<LeaveLogicModel>("leaves1");
collection.InsertOne(leaveLogic);
}
Now this is the MongoDB table that saves as a previous date.
Here you can see that my StartDate is Apr-02-2018 but it saves as Apr-01-2018 and for all date it is the same.
Can someone tell me where I am wrong?
When you create new dates with just date or date and time, it usually creates them in the same timezone as the program is.
So if you dont specify the timezone, it becomes the timezone the server is in. When you save to Mongo, the Date is serialized to UTC -> zero timezone.
Create the dates with +00:00 timezone and you should have consistent data.
It's a good practice to set your datetimes to UTC, however if you want to convert it, you can use something like this.
var date = DateTime.UtcNow;
TimeZoneInfo.ConvertTime(date, TimeZoneInfo.Local);

comparing date value in inputbox using if else in javascript

my code below is in javascript, $('#date_start').change(function(){ is working fine, but when im using if else statement to compare the date inputted in my inputbox from the current date, nothing happens at all.
$(document).ready(function() {
$('#date_start').change(function(){
var startdate = $('#date_start').datepicker("getDate");
var today = new Date();
var tomorrow = today.add(2).day();
if(startdate.getTime() < today.getTime()){
document.getElementById('finish').disabled = true;
}
else{
Remove Time from both of Date and compare it.
String input = "2012/01/20 12:05:10.321";
DateFormat inputFormatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS");
Date date = inputFormatter.parse(input);
DateFormat outputFormatter = new SimpleDateFormat("MM/dd/yyyy");
String output = outputFormatter.format(date);

ReferenceError: date is not defined

I have some code here where I get a value from a form represented by "adate". Then I split the string the user enters at the hyphen and separate each value into year, month and day as you can see. I use those values to define a date object. My console correctly displays the date, but I keep getting this error also showing up. Am I defining the date incorrectly? I'm not sure what the issue is.
function getFormData() {
var task = document.getElementById("task").value;
if (checkInputText(task, "Please enter a task")) return;
var who = document.getElementById("who").value;
if (checkInputText(who, "Please enter a person to do the task")) return;
var adate = document.getElementById("dueDate").value;
var reString = new RegExp("[0-9]{4}\\-\[0-9]{2}\\-\[0-9]{2}");
if ( adate.match(reString)) {
processDate(adate) }
else {
alert("you did not enter the date in the correct format")
};
var id = (new Date()).getTime();
var todoItem = new Todo(id, task, who, date);
todos.push(todoItem);
addTodoToPage(todoItem);
saveTodoItem(todoItem);
hideSearchResults();
}
function processDate(adate) {
var splitArray = new Array();
splitArray = adate.split("-");
var year = splitArray[0];
var month = splitArray[1] - 1;
var day = splitArray[2];
var date = new Date(year, month, day);
console.log(date);
}
Make your function return the date, because the date variable in there is not visible to the outside:
function processDate(adate) {
var splitArray = new Array();
splitArray = adate.split("-");
var year = splitArray[0];
var month = splitArray[1] - 1;
var day = splitArray[2];
return new Date(year, month, day);
}
Then assign to a new variable when you call it:
var date = processDate(adate);
The error actually originated in the following line, because you were referencing a non-existing date variable:
var todoItem = new Todo(id, task, who, date);
Just a comment.
The RegExp constructor is usually only required where the expression is dynamically generated. Where you have a fixed expression, it's simpler to use a literal (as you don't have to quote certain characters). Also, to test the format, a more appropriate method is test rather than match.
If the date format is: yyyy-mm-dd, consider:
var reString = /^\d{4}-\d\d-\d\d$/; // trim leading and trailing white space?
if (reString.test(adate)) {
processDate(adate);
}
The date string validation should be in the processDate function, which might throw different errors depending on whether the format is incorrect or the date is invalid (e.g. 2013-02-29, which will return a date of 2013-03-01 in your current code).

Categories

Resources