Comparing 2 date values and checking difference between the 2 in minutes - javascript

I have a sheet with a time trigger set to run every 30 minutes. When the trigger happens a function is executed which will add a new row at the bottom of the sheet with some data.
On column A I have dates.
Now the problem is sometimes the Google's trigger tool by error will execute like 3 times in a row or more with less then a minute in between each execution. This happens more often than I'd like and I need a way to fix this.
I wrote some code which supposedly will delete the new recorded row if the difference between this last row and the second last row, or previous row, is less than 30 minutes. This way all the rows will always be 30 minutes apart from each other.
I'm stuck at this point where I can't figure out a way of making Google Script to compare 2 dates and return TRUE or FALSE based on my condition, which is to check if the difference between 2 dates is more/equal or less than 30 minutes, and if it is less to delete the row, otherwise do nothing. Actually I gave the condition a margin of 1 minutes because the triggers are not 100% exact and don't always happen at the same second.
The variable timerDifference returns NaN.
I suspect it might be because of the date format?
This is my code ATM:
function deleteTriggerError() {
let logSheetName = "LOG";
let logSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(logSheetName);
let lastRowTimer = logSheet.getRange(logSheet.getLastRow(), 1).getValue();
let secondLastRowTimer = logSheet.getRange(logSheet.getLastRow() - 1, 1).getValue();
console.log(lastRowTimer);
console.log(secondLastRowTimer);
let dysLast = Utilities.formatDate(lastRowTimer, timeZone, 'dd/mm/yyyy hh:mm:ss');
let dysSecondLast = Utilities.formatDate(secondLastRowTimer, timeZone, 'dd/mm/yyyy hh:mm:ss');
console.log(dysSecondLast);
console.log(dysLast);
let timerDifference = dysLast - dysSecondLast;
console.log(timerDifference);
let timerDifLimitRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(logSheetName).getRange("H3");
let timerDifLimitValueTXT = timerDifLimitRange.getValue();
let timerDifLimitValue;
//console.log(timerDifference);
timerDifLimitValue = timerDifLimitValueTXT.replace("3 0 M I N U T E S", 30 - 1);
logSheet.appendRow([""]);
if (timerDifference < timerDifLimitValue) {
logSheet.deleteRow(logSheet.getLastRow());
// console.log("TRUE");
} else {
// console.log("FALSE");
}
}
I tried the solution I saw here:
Time difference between two time showing wrong values in js
var diff = Math.abs(new Date('01/23/2020 06:30 PM') - new Date('01/23/2020 05:00 AM'));
var minutes = Math.floor((diff/1000)/60);
alert(minutes);
This solution will only work with en_US date format. But I'm using en_GB date format:21/09/2021 14:44:38. Any reason why?
You can check:
var diff = Math.abs(new Date('01/23/2020 06:30 PM') - new Date('01/23/2020 05:00 AM'));
console.log(diff);
var minutes = Math.floor((diff/1000)/60);
console.log(minutes);
var diff = Math.abs(new Date('21/09/2021 14:44:38') - new Date('21/09/2021 14:04:38'));
console.log(diff);
var minutes = Math.floor((diff/1000)/60);
console.log(minutes);
var diff = Math.abs(new Date('09/21/2021 14:44:38') - new Date('09/21/2021 14:04:38'));
console.log(diff);
var minutes = Math.floor((diff/1000)/60);
console.log(minutes);
Thank you for your time.
My file:
https://docs.google.com/spreadsheets/d/1ExXtmQ8nyuV1o_UtabVJ-TifIbORItFMWjtN6ZlruWc/edit?usp=sharing

Date() doesn't support dd/mm/yyyy. This prevents ambiguity for cases like 1/2/2014 that yields into 2 possible dates, Jan 2 and Feb 1. So it only supports the mm/dd/yyyy as its standard format.
One way to converting it properly is to split the date.
function myFunction() {
startDate = '21/09/2021 14:44:38';
endDate = '21/09/2021 14:04:38';
var diff = Math.abs(convertGBDatetoDate(startDate) - convertGBDatetoDate(endDate));
console.log(diff);
var minutes = Math.floor((diff/1000)/60);
console.log(minutes);
}
function convertGBDatetoDate(string){
var [sD, sM, sY] = string.split(' ')[0].split('/').map(i=>Number(i));
var [sh, sm, ss] = string.split(' ')[1].split(':').map(i=>Number(i));
return new Date(sY,sM - 1,sD,sh,sm,ss);
}

Someone commented above, but then deleted, to use getTime().
Read here.
So I think this works. I don't even need to worry about date formats. I can just get the range with getRange() and getValue(). Then I can use this simple code:
var end, start;
start = new Date("Tue Sep 21 2021 20:00:00 GMT+0100 (British Summer Time)");
end = new Date("Tue Sep 21 2021 20:33:17 GMT+0100 (British Summer Time)");
console.log('Operation took ' + (((end.getTime() - start.getTime())/1000)/60) + ' min');

Related

getHours function not working in date difference

[code][1]
Hi I am trying to find the difference between these 2 dates and would like the answer to be set like this - 00:00:00. I have "current" set to a as 00:00:00 but would like the time stamp to be updated to however many hours, min, seconds there are between the 2 days. I'm being told that the getHours, getMinutes, and getSeconds function is not a thing. How do I go about fixing this? [1]: https://i.stack.imgur.com/1GY5B.png
I guess you didnt convert the time to a Date.
look at my example:
function updateTime(){
var event = new Date("April 1, 2021 8:30:00").getTime();
var now = new Date().getTime();
var a = (event - now);
var d = new Date(a);
var hours = d.getHours(),
minutes = d.getMinutes(),
seconds = d.getSeconds(),
ampm = "AM";
if (hours>12) ampm = "PM";
console.log(`${hours}:${minutes}:${seconds} ${ampm}`)
}
updateTime();
Is this what you try to do?
PS:
However I would also multiply the hours with the days or I would also add days if days > 0
And the "AM" is kinda unnecessary for getting a difference

Check if time between 2 times in Javascript

I'm using google sheets javascript script where I'm looping over 15 min intervals each in their own column. I'm trying to find the column that matches the current hour/min so I can highlight it but can't get the javascript time checking to work.
time and nextTime are simply times like 8:00 or 8:15, so when I convert them to Date I get something like: Sat Dec 30 1899 08:00:00 GMT-0600 (CST)
Does getTime() consider the date part or just the time part? If I have a string for the date like "10/14/2017" how could I bring the 2 together for the date object?
var now = new Date().getTime();
for(i in data[0]){
var time = new Date(data[0][i]);
var nextTime = new Date(data[0][Number(i) + 1]);
var diff1 = time.getTime() - now;
var diff2 = nextTime.getTime() - now;
if(now >= time.getTime() && now < nextTime.getTime()){
Logger.log(time);
}
}
The getTime() method returns the number of milliseconds elapsed since 1 January 1970 00:00:00 UTC.
This number is called a timestamp. e.g. 1508001790301. This number represents the total number of milliseconds (so it considers both the date part and the time part)
You can convert the string "10/14/2017" to a timestamp by passing it as a Date constructor argument and calling the getTime method on the newly created date object.
e.g.
var nextTime = new Date('10/14/2017').getTime(); This will return the number of milliseconds that have passed since January 1970 till Oct 14 2017 00:00:00.
To bring everything together:
1) Get the current timestamp
var now = new Date().getTime(); // 1508001790301
2) Get the timestamps for time and nextTime
var time = new Date('10/14/2017').getTime();
var nextTime = new Date('10/15/2017').getTime();
3) Simply compare the values as you did already in the example
if(time <= now && now <= nextTime) {
// Highlight the column
}

How do I convert UTC/ GMT datetime to CST in Javascript? (not local, CST always)

I have a challenge where backend data is always stored in UTC time. Our front-end data is always presented in CST. I don't have access to this 'black box.'
I would like to mirror this in our data warehouse. Which is based in Europe (CET). So "local" conversion will not work.
I'm wondering the simplest, most straightforward way to accurately convert UTC time (I can have it in epoch milliseconds or a date format '2015-01-01 00:00:00') to Central Standard Time. (which is 5 or 6 hours behind based on Daylight Savings).
I see a lot of threads about converting to 'local' time ... again I don't want this, nor do I simply want to subtract 6 hours which will be wrong half the year.
Anyone have any ideas? This seems to be a very common problem but I've been searching for a while, and have found nothing.
Using moment.js with the moment-timezone add-on makes this task simple.
// construct a moment object with UTC-based input
var m = moment.utc('2015-01-01 00:00:00');
// convert using the TZDB identifier for US Central time
m.tz('America/Chicago');
// format output however you desire
var s = m.format("YYYY-MM-DD HH:mm:ss");
Additionally, since you are referring to the entire North American Central time zone, you should say either "Central Time", or "CT". The abbreviation "CST" as applied to North America explicitly means UTC-6, while the "CDT" abbreviation would be used for UTC-5 during daylight saving time.
Do be careful with abbreviations though. "CST" might mean "China Standard Time". (It actually has five different interpretations).
You can use the time zone offset to determine whether 5 or 6 hours should be subtracted.
var dateJan;
var dateJul;
var timezoneOffset;
var divUTC;
var divCST;
// Set initial date value
dateValue = new Date('10/31/2015 7:29:54 PM');
divUTC = document.getElementById('UTC_Time');
divCST = document.getElementById('CST_Time');
divUTC.innerHTML = 'from UTC = ' + dateValue.toString();
// Get dates for January and July
dateJan = new Date(dateValue.getFullYear(), 0, 1);
dateJul = new Date(dateValue.getFullYear(), 6, 1);
// Get timezone offset
timezoneOffset = Math.max(dateJan.getTimezoneOffset(), dateJul.getTimezoneOffset());
// Check if daylight savings
if (dateValue.getTimezoneOffset() < timezoneOffset) {
// Adjust date by 5 hours
dateValue = new Date(dateValue.getTime() - ((1 * 60 * 60 * 1000) * 5));
}
else {
// Adjust date by 6 hours
dateValue = new Date(dateValue.getTime() - ((1 * 60 * 60 * 1000) * 6));
}
divCST.innerHTML = 'to CST = ' + dateValue.toString();
<div id="UTC_Time"></div>
<br/>
<div id="CST_Time"></div>
Maybe you can use something like the following. Note, that is just an example you might need to adjust it to your needs.
let cstTime = new Date(createdAt).toLocaleString("es-MX", {
timeZone: "America/Mexico_City" });
You can use below code snippet for converting.
function convertUTCtoCDT() {
var timelagging = 6; // 5 or 6
var utc = new Date();
var cdt = new Date(utc.getTime()-((1 * 60 * 60 * 1000) * timelagging));
console.log("CDT: "+cdt);
}
let newDate = moment(new Date()).utc().format("YYYY-MM-DD HH:mm:ss").toString()
var m = moment.utc(newDate);
m.tz('America/Chicago');
var cstDate = m.format("YYYY-MM-DD HH:mm:ss");
You can use below code snippet
// Get time zone offset for CDT or CST
const getCdtCstOffset = () => {
const getNthSunday = (date, nth) => {
date.setDate((7*(nth-1))+(8-date.getDay()));
return date;
}
const isCdtTimezoneOffset = (today) => {
console.log('Today : ', today);
let dt = new Date();
var mar = new Date(dt.getFullYear(), 2, 1);
mar = getNthSunday(mar, 2);
console.log('CDT Start : ', mar);
var nov = new Date(dt.getFullYear(), 10, 1, 23, 59, 59);
nov = getNthSunday(nov, 1);
console.log('CDT End : ', nov);
return mar.getTime()< today.getTime() && nov.getTime()> today.getTime();
}
var today = new Date()// current date
if (isCdtTimezoneOffset(today)) {
return -5
} else {
return -6
}
}
let cstOrCdt = new Date();
cstOrCdt.setHours(cstOrCdt.getHours()+getCdtCstOffset())
console.log('CstOrCdt : ', cstOrCdt);

Time between two times on current date

I am trying to calculate the time between two times on the current date using JavaScript. There are other questions similar to this one, but none seem to work, and few with many upvotes that I can find.
I have the following, which fails on the line: var diff = new Date(time1 - time2);, which always gives me an invalid Date when alerted, so it is clearly failing. I cannot work out why.
The initial date is added in the format of: hh:mm:ss in an input field. I am using jQuery.
$(function(){
$('#goTime').click(function(){
var currentDate = new Date();
var dateString = (strpad(currentDate.getDate()) +'-'+ strpad(currentDate.getMonth()+1)+'-'+currentDate.getFullYear()+' '+ $('#starttime').val());
var time1 = new Date(dateString).getTime();
var time2 = new Date().getTime();
var diff = new Date(time1 - time2);
var hours = diff.getHours();
var minutes = diff.getMinutes();
var seconds = diff.getMinutes();
alert(hours + ':' + minutes + ':' + seconds);
});
});
function strpad(val){
return (!isNaN(val) && val.toString().length==1)?"0"+val:val;
}
dateString is equal to: 14-01-2013 23:00
You have the fields in dateString backwards. Swap the year and day fields...
> new Date('14-01-2013 23:00')
Invalid Date
> new Date('2013-01-14 23:00')
Mon Jan 14 2013 23:00:00 GMT-0800 (PST)
dd-MM-yyyy HH:mm is not recognized as a valid time format by new Date(). You have a few options though:
Use slashes instead of dashes: dd/MM/yyyy HH:mm date strings are correctly parsed.
Use ISO date strings: yyyy-MM-dd HH:mm are also recognized.
Build the Date object yourself.
For the second option, since you only really care about the time, you could just split the time string yourself and pass them to Date.setHours(h, m, s):
var timeParts = $('#starttime').val().split(':', 2);
var time1 = new Date();
time1.setHours(timeParts[0], timeParts[1]);
You are experiencing an invalid time in your datestring. time1 is NaN, and so diff will be. It might be better to use this:
var date = new Date();
var match = /^(\d+):(\d+):(\d+)$/.exec($('#starttime').val()); // enforcing format
if (!match)
return alert("Invalid input!"); // abort
date.setHours(parseInt(match[1], 10));
date.setMinutes(parseInt(match[2], 10));
date.setSeconds(parseInt(match[3], 10));
var diff = Date.now() - date;
If you are trying to calculate the time difference between two dates, then you do not need to create a new date object to do that.
var time1 = new Date(dateString).getTime();
var time2 = new Date().getTime();
var diff = time1 - time2;// number of milliseconds
var seconds = diff/1000;
var minutes = seconds/60;
var hours = minutes/60;
Edit: You will want to take into account broofa's answer as well to
make sure your date string is correctly formatted
The getTime function returns the number of milliseconds since Jan 1, 1970. So by subtracting the two values you are left with the number of milliseconds between each date object. If you were to pass that value into the Date constructor, the resulting date object would not be what you are expecting. see getTime

Concatenate a date and time value

i need to concatenate a date value and a time value to make one value representing a datetime in javascript.
thanks,
daniel
Working with strings is fun and all, but let's suppose you have two datetimes and don't like relying on strings.
function combineDateWithTime(d, t)
{
return new Date(
d.getFullYear(),
d.getMonth(),
d.getDate(),
t.getHours(),
t.getMinutes(),
t.getSeconds(),
t.getMilliseconds()
);
}
Test:
var taxDay = new Date(2016, 3, 15); // months are 0-indexed but years and dates aren't.
var clockout = new Date(0001, 0, 1, 17);
var timeToDoTaxes = combineDateWithTime(taxDay, clockout);
// yields: Fri Apr 15 2016 17:00:00 GMT-0700 (Pacific Daylight Time)
I could not make the accepted answer work so used moment.js
date = moment(selected_date + ' ' + selected_time, "YYYY-MM-DD HH:mm");
date._i "11-06-2014 13:30"
Assuming "date" is the date string and "time" is the time string:
// create Date object from valid string inputs
var datetime = new Date(date+' '+time);
// format the output
var month = datetime.getMonth()+1;
var day = datetime.getDate();
var year = datetime.getFullYear();
var hour = this.getHours();
if (hour < 10)
hour = "0"+hour;
var min = this.getMinutes();
if (min < 10)
min = "0"+min;
var sec = this.getSeconds();
if (sec < 10)
sec = "0"+sec;
// put it all togeter
var dateTimeString = month+'/'+day+'/'+year+' '+hour+':'+min+':'+sec;
Depending on the type of the original date and time value there are some different ways to approach this.
A Date object (which has both date and time) may be created in a number of ways.
birthday = new Date("December 17, 1995 03:24:00");
birthday = new Date(1995,11,17);
birthday = new Date(1995,11,17,3,24,0);
If the original date and time also is objects of type Date, you may use getHours(), getMinutes(), and so on to extract the desired values.
For more information, see Mozilla Developer Center for the Date object.
If you provide more detailed information in your question I may edit the answer to be more specific.

Categories

Resources