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
}
Related
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');
I am having a date range from June 21 to Jun 27.I want to add 20 minutes to my start date every 5secs and make a service call to get some values. Also, for the second service call I need my previous end datetime as start datetime.For example for service call 1,
my start date is Jun 21, 5:00 PM
my end date is Jun 27, 5:20 PM
my second service call should have
start date as Jun 21, 5:20 PM
end date as Jun 21 , 5:40 PM
How can I achieve this through javascript and also how do I change date once I pass 24 hrs.
Thanks!
//My start date and end date
var startDt = newDate(data.startDate);
var endDt = newDate(data.endDate);
var count = 0;
setInterval(function()
{
if(count == 0){
var sDt= new Date(startDt).toISOString();
var eDt= new Date(startDt.setMinutes(startDt.getMinutes() + 10)).toISOString();
}
else{
var sDt = new Date(startDt.setMinutes(startDt.getMinutes() + )).toISOString();
}
//calling my apy with sDt and eDt here;
count++;
},5000)
The Javascript setMinutes() method will automatically go to the next hour or day when the minutes or hour wrap around.
startTime = new Date(endTime); // Copy old endTime to startTime
endTime.setMinutes(endTime.getMinutes() + 20); // add 20 minutes to endTime
Here's the full code:
//My start date and end date
var startDt = newDate(data.startDate);
var endDt = newDate(data.endDate);
var count = 0;
var interval = setInterval(function()
{
if (new Date() > endDt) { // Reached the endDt
clearInterval(interval);
return;
}
var sDt = new Date(startDt).toISOString();
var eDt = new Date(startDt.setMinutes(startDt.getMinutes() + 20)).toISOString();
//calling my apy with sDt and eDt here;
count++;
},5000)
if you want to run a function every five seconds
var dt = new Date(2016,6,21)
setTimeOut(function(){
//add 20 minutes to dt
dt = new Date(dt.getTime()+(20*60000)) // dt will be your start time
//end time is add 20 minutes to start time
var endDT = new Date(dt.getTime()+(20*60000));
//now call you ajax, return what ever you need along with dt and endDT
},5000//five seconds);
you could use momentjs to add seconds to your startDate like this
var startDate = moment('Jun 21, 5:00 PM');
startDate.add('20','minutes');
it will automatically maintain the coherence of the timestamps
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
Total newbie at JavaScript.
I would like to calculate how many days one has been alive by asking the user their date of birth via prompts/alerts, then obviously subtracting their date of birth from today's date.
I've made a bit of a start...
var month=prompt("Please enter month of birth"," ");
var day=prompt("Please enter day of birth"," ");
var year=prompt("Please enter your year of birth"," ");
var curdate = this is the bit i need help with
var birth = this is the bit i need help with
var milliDay = 1000 * 60 * 60 * 24; // a day in milliseconds;
var ageInDays = (curdate - birth) / milliDay;
document.write("You have been alive for: " + ageInDays);
Any advice or help would be much appreciated.
You need to use the Date object (MDN). They can be created from a month, a day, and a year, and added/subtracted.
Typically :
var curDate = new Date();
var birth = new Date(year, month, day);
var ageInDays = (curdate.getTime() - birth.getTime()) / milliDay;
Be aware of the fact that months starts at 0, e.g. January is 0.
var curDate = new Date();
gives you the current date.
var birthdate = new Date(year, month-1, day);
gives you a Date from the separate variables. NB the month is zero-based.
end = Date.now(); // Get current time in milliseconds from 1 Jan 1970
var date = 20; //Date you got from the user
var month = 8-1; // Month, subtracted by one because month starts from 0 according to JS
var year = 1996; // Year
//Set date to the old time
obj = new Date();
obj.setDate(date);
obj.setMonth(month);
obj.setYear(year);
obj = obj.getTime(); //Get old time in milliseconds from Jan 1 1970
document.write((end-obj)/(1000*60*60*24));
Simply subtract current time from Jan 1 1970 in milliseconds from their birthdate's time from Jan 1 1970 in milliseconds. Then convert it to days. Look at MDN's Docs for more info.
See JSFiddle for a working example. Try entering yesterday's date. It should show 1 day.
Read some of this: http://www.w3schools.com/js/js_obj_date.asp
In an JS app, I receive timestamp (eq. 1270544790922) from server (Ajax).
Basing on that timestamp I create Date object using:
var _date = new Date();
_date.setTime(1270544790922);
Now, _date decoded timestamp in current user locale time zone. I don't want that.
I would like _date to convert this timestamp to current time in city of Helsinki in Europe (disregarding current time zone of the user).
How can I do that?
A Date object's underlying value is actually in UTC. To prove this, notice that if you type new Date(0) you'll see something like: Wed Dec 31 1969 16:00:00 GMT-0800 (PST). 0 is treated as 0 in GMT, but .toString() method shows the local time.
Big note, UTC stands for Universal time code. The current time right now in 2 different places is the same UTC, but the output can be formatted differently.
What we need here is some formatting
var _date = new Date(1270544790922);
// outputs > "Tue Apr 06 2010 02:06:30 GMT-0700 (PDT)", for me
_date.toLocaleString('fi-FI', { timeZone: 'Europe/Helsinki' });
// outputs > "6.4.2010 klo 12.06.30"
_date.toLocaleString('en-US', { timeZone: 'Europe/Helsinki' });
// outputs > "4/6/2010, 12:06:30 PM"
This works but.... you can't really use any of the other date methods for your purposes since they describe the user's timezone. What you want is a date object that's related to the Helsinki timezone. Your options at this point are to use some 3rd party library (I recommend this), or hack-up the date object so you can use most of it's methods.
Option 1 - a 3rd party like moment-timezone
moment(1270544790922).tz('Europe/Helsinki').format('YYYY-MM-DD HH:mm:ss')
// outputs > 2010-04-06 12:06:30
moment(1270544790922).tz('Europe/Helsinki').hour()
// outputs > 12
This looks a lot more elegant than what we're about to do next.
Option 2 - Hack up the date object
var currentHelsinkiHoursOffset = 2; // sometimes it is 3
var date = new Date(1270544790922);
var helsenkiOffset = currentHelsinkiHoursOffset*60*60000;
var userOffset = _date.getTimezoneOffset()*60000; // [min*60000 = ms]
var helsenkiTime = new Date(date.getTime()+ helsenkiOffset + userOffset);
// Outputs > Tue Apr 06 2010 12:06:30 GMT-0700 (PDT)
It still thinks it's GMT-0700 (PDT), but if you don't stare too hard you may be able to mistake that for a date object that's useful for your purposes.
I conveniently skipped a part. You need to be able to define currentHelsinkiOffset. If you can use date.getTimezoneOffset() on the server side, or just use some if statements to describe when the time zone changes will occur, that should solve your problem.
Conclusion - I think especially for this purpose you should use a date library like moment-timezone.
To account for milliseconds and the user's time zone, use the following:
var _userOffset = _date.getTimezoneOffset()*60*1000; // user's offset time
var _centralOffset = 6*60*60*1000; // 6 for central time - use whatever you need
_date = new Date(_date.getTime() - _userOffset + _centralOffset); // redefine variable
Just another approach
function parseTimestamp(timestampStr) {
return new Date(new Date(timestampStr).getTime() + (new Date(timestampStr).getTimezoneOffset() * 60 * 1000));
};
//Sun Jan 01 2017 12:00:00
var timestamp = 1483272000000;
date = parseTimestamp(timestamp);
document.write(date);
Cheers!
I have a suspicion, that the Answer doesn't give the correct result. In the question the asker wants to convert timestamp from server to current time in Hellsinki disregarding current time zone of the user.
It's the fact that the user's timezone can be what ever so we cannot trust to it.
If eg. timestamp is 1270544790922 and we have a function:
var _date = new Date();
_date.setTime(1270544790922);
var _helsenkiOffset = 2*60*60;//maybe 3
var _userOffset = _date.getTimezoneOffset()*60*60;
var _helsenkiTime = new Date(_date.getTime()+_helsenkiOffset+_userOffset);
When a New Yorker visits the page, alert(_helsenkiTime) prints:
Tue Apr 06 2010 05:21:02 GMT-0400 (EDT)
And when a Finlander visits the page, alert(_helsenkiTime) prints:
Tue Apr 06 2010 11:55:50 GMT+0300 (EEST)
So the function is correct only if the page visitor has the target timezone (Europe/Helsinki) in his computer, but fails in nearly every other part of the world. And because the server timestamp is usually UNIX timestamp, which is by definition in UTC, the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT), we cannot determine DST or non-DST from timestamp.
So the solution is to DISREGARD the current time zone of the user and implement some way to calculate UTC offset whether the date is in DST or not. Javascript has not native method to determine DST transition history of other timezone than the current timezone of user. We can achieve this most simply using server side script, because we have easy access to server's timezone database with the whole transition history of all timezones.
But if you have no access to the server's (or any other server's) timezone database AND the timestamp is in UTC, you can get the similar functionality by hard coding the DST rules in Javascript.
To cover dates in years 1998 - 2099 in Europe/Helsinki you can use the following function (jsfiddled):
function timestampToHellsinki(server_timestamp) {
function pad(num) {
num = num.toString();
if (num.length == 1) return "0" + num;
return num;
}
var _date = new Date();
_date.setTime(server_timestamp);
var _year = _date.getUTCFullYear();
// Return false, if DST rules have been different than nowadays:
if (_year<=1998 && _year>2099) return false;
// Calculate DST start day, it is the last sunday of March
var start_day = (31 - ((((5 * _year) / 4) + 4) % 7));
var SUMMER_start = new Date(Date.UTC(_year, 2, start_day, 1, 0, 0));
// Calculate DST end day, it is the last sunday of October
var end_day = (31 - ((((5 * _year) / 4) + 1) % 7))
var SUMMER_end = new Date(Date.UTC(_year, 9, end_day, 1, 0, 0));
// Check if the time is between SUMMER_start and SUMMER_end
// If the time is in summer, the offset is 2 hours
// else offset is 3 hours
var hellsinkiOffset = 2 * 60 * 60 * 1000;
if (_date > SUMMER_start && _date < SUMMER_end) hellsinkiOffset =
3 * 60 * 60 * 1000;
// Add server timestamp to midnight January 1, 1970
// Add Hellsinki offset to that
_date.setTime(server_timestamp + hellsinkiOffset);
var hellsinkiTime = pad(_date.getUTCDate()) + "." +
pad(_date.getUTCMonth()) + "." + _date.getUTCFullYear() +
" " + pad(_date.getUTCHours()) + ":" +
pad(_date.getUTCMinutes()) + ":" + pad(_date.getUTCSeconds());
return hellsinkiTime;
}
Examples of usage:
var server_timestamp = 1270544790922;
document.getElementById("time").innerHTML = "The timestamp " +
server_timestamp + " is in Hellsinki " +
timestampToHellsinki(server_timestamp);
server_timestamp = 1349841923 * 1000;
document.getElementById("time").innerHTML += "<br><br>The timestamp " +
server_timestamp + " is in Hellsinki " + timestampToHellsinki(server_timestamp);
var now = new Date();
server_timestamp = now.getTime();
document.getElementById("time").innerHTML += "<br><br>The timestamp is now " +
server_timestamp + " and the current local time in Hellsinki is " +
timestampToHellsinki(server_timestamp);
And this print the following regardless of user timezone:
The timestamp 1270544790922 is in Hellsinki 06.03.2010 12:06:30
The timestamp 1349841923000 is in Hellsinki 10.09.2012 07:05:23
The timestamp is now 1349853751034 and the current local time in Hellsinki is 10.09.2012 10:22:31
Of course if you can return timestamp in a form that the offset (DST or non-DST one) is already added to timestamp on server, you don't have to calculate it clientside and you can simplify the function a lot. BUT remember to NOT use timezoneOffset(), because then you have to deal with user timezone and this is not the wanted behaviour.
Presuming you get the timestamp in Helsinki time, I would create a date object set to midnight January 1 1970 UTC (for disregarding the local timezone settings of the browser).
Then just add the needed number of milliseconds to it.
var _date = new Date( Date.UTC(1970, 0, 1, 0, 0, 0, 0) );
_date.setUTCMilliseconds(1270544790922);
alert(_date); //date shown shifted corresponding to local time settings
alert(_date.getUTCFullYear()); //the UTC year value
alert(_date.getUTCMonth()); //the UTC month value
alert(_date.getUTCDate()); //the UTC day of month value
alert(_date.getUTCHours()); //the UTC hour value
alert(_date.getUTCMinutes()); //the UTC minutes value
Watch out later, to always ask UTC values from the date object. This way users will see the same date values regardless of local settings.
Otherwise date values will be shifted corresponding to local time settings.
My solutions is to determine timezone adjustment the browser applies, and reverse it:
var timestamp = 1600913205; //retrieved from unix, that is why it is in seconds
//uncomment below line if you want to apply Pacific timezone
//timestamp += -25200;
//determine the timezone offset the browser applies to Date()
var offset = (new Date()).getTimezoneOffset() * 60;
//re-initialize the Date function to reverse the timezone adjustment
var date = new Date((timestamp + offset) * 1000);
//here continue using date functions.
This point the date will be timezone free and always UTC, You can apply your own offset to timestamp to produce any timezone.
Use this and always use UTC functions afterwards e.g. mydate.getUTCHours();
function getDateUTC(str) {
function getUTCDate(myDateStr){
if(myDateStr.length <= 10){
//const date = new Date(myDateStr); //is already assuming UTC, smart - but for browser compatibility we will add time string none the less
const date = new Date(myDateStr.trim() + 'T00:00:00Z');
return date;
}else{
throw "only date strings, not date time";
}
}
function getUTCDatetime(myDateStr){
if(myDateStr.length <= 10){
throw "only date TIME strings, not date only";
}else{
return new Date(myDateStr.trim() +'Z'); //this assumes no time zone is part of the date string. Z indicates UTC time zone
}
}
let rv = '';
if(str && str.length){
if(str.length <= 10){
rv = getUTCDate(str);
}else if(str.length > 10){
rv = getUTCDatetime(str);
}
}else{
rv = '';
}
return rv;
}
console.info(getDateUTC('2020-02-02').toUTCString());
var mydateee2 = getDateUTC('2020-02-02 02:02:02');
console.info(mydateee2.toUTCString());
// you are free to use all UTC functions on date e.g.
console.info(mydateee2.getUTCHours())
console.info('all is good now if you use UTC functions')