getHours function not working in date difference - javascript

[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

Related

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

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');

Get the correct local time

I need to get the local time. I created this script but, for example, in italy ( where I live ), the alert shows 7 instead of 9. Why ?
var time = new Date().getTime();
var seconds = time / 1000;
seconds = seconds % 86400;
hours = parseInt(seconds / 3600);
alert(hours);
Because getTime returns the timestamp in milliseconds. And the timestamp is timezone independent. Use getTimezoneOffset() to get the offset in minutes from UTC, and add it.
new Date().getHours() will give you the local time, no adjustment needed.
new Date().getTimezoneOffset() will give you the number of minutes from UTC in the users's locale, should you need to offset an absolute time.
Note that UNIX timestamps measure the number of seconds since the UNIX epoch as if every day was exactly 3600 * 24 seconds. That allows you to get the time on most days with divisions and modulos, but if your timestamp is earlier than the latest leap second, and you try to do some simple maths with it, the result will not be accurate.
DEMO : http://jsfiddle.net/yk3wkcr8/
var currentTime = new Date();
var h = currentTime.getHours();
var m = currentTime.getMinutes();
var s = currentTime.getSeconds();
alert(h);
alert(m);
alert(s);
If you want an example, try this: Fiddle
It uses full array with seconds, minutes, hours, date, day and year.
BTW you can use getHours(); followed by the others.
var d = new Date(),
hours = d.getHours(),
hour = (hours - 12),
year = d.getFullYear(),
second = d.getSeconds(),
minute = d.getMinutes();
alert (hour + ":" + minute + ":" + second);
etc, etc.
You can try this:
new Date().toLocaleString()
it will give you something like:
"4/16/2015, 9:14:53 AM"
And if you need to obtain only the time stamp then you can split the resulting string into an array and get the second item from the array:
new Date().toLocaleString().split(',')[1]
If you need only the hours this is the way:
new Date().getHours()

how to find difference in days between day and month irrespective of years

I want to know the difference between to two dates irrespective of year..
For Example : format date/month/year
For example difference of today date to some date lets take 01/06
The expected answer for this will be around 185 days..
I tried below example..Let me know whats wrong with this
var a = moment('06/01','M/D');
console.log(a);
var b = moment();
console.log(b);
var diffDays = b.diff(a, 'days');
alert(diffDays);
I dont want to use momet.js atmost. If it can be done with javascript its so good for me.
A nice trick could be to set the year to always the same.
var a = moment('2015/06/01','Y/M/D');
console.log(a);
var b = moment().set('year', 2015);
console.log(b);
var diffDays = b.diff(a, 'days');
alert(diffDays);
The problem about your question in general is how to deal with leap years; how the script should know the difference between 2/20 and 3/1 ? You have to consider how to solve this.
Barth Zaleweski is 100% on track with that. If you want to use straight javascript:
var today = new Date();
var otherDate = new Date(today);
otherDate.setMonth(5); // Set the month (on scale from 0 to 11)
otherDate.setDate(1); // set day
var seconds = (otherDate.getTime() - today.getTime()) / 1000;
var minutes = seconds / 60;
var hours = minutes / 60;
var days = hours / 24;
console.log(days);
There are methods for setting hour/minute/second as well, but if you don't do anything they'll be the same as the start, and you can obviously call those same methods on your start time if you don't want to use today.
Can try using this:
var str1 = '06/01', str2 = '02/28', d1, d2, diff;
function setDate(str, date) {
var date = new Date(),
dateParts = str.split('/'),
monthIndex = parseInt(dateParts[0], 10) - 1,
day = parseInt(dateParts[1], 10);
date.setMonth(monthIndex);
date.setDate(day);
return date
}
d1 = setDate(str1);
d2 = setDate(str2);
diff = Math.round(Math.abs((d1 - d2) / (24 * 60 * 60 * 1000)))
console.log(diff) // returns 93
The rounding is due to differences in daylight savings (or other locale time shifts within the year) that can cause decimal values returned.
It is probably better to use UTC for this
If current year is leap year and dates span end of February then Feb 29 would also be counted
DEMO
If it is this year then I am getting a difference of 147 using a library that I have been working on (AstroDate) which doesn't rely on javascript's Date object, it's all done with pure math.
require.config({
paths: {
'astrodate': '//rawgit.com/Xotic750/astrodate/master/lib/astrodate'
}
});
require(['astrodate'], function (AstroDate) {
"use strict";
var diff = new AstroDate("2015","6","1").jd() - new AstroDate("2015","1","5").jd();
document.body.appendChild(document.createTextNode(diff));
});
<script src="http://requirejs.org/docs/release/2.1.8/minified/require.js"></script>
If it was next year, which is a leap year then I am getting 148
require.config({
paths: {
'astrodate': '//rawgit.com/Xotic750/astrodate/master/lib/astrodate'
}
});
require(['astrodate'], function (AstroDate) {
"use strict";
var diff = new AstroDate("2016", "6", "1").jd() - new AstroDate("2016", "1", "5").jd();
document.body.appendChild(document.createTextNode(diff));
});
<script src="http://requirejs.org/docs/release/2.1.8/minified/require.js"></script>

Comparing two dates in JavaScript

I am currently trying to compare the launch_date with today's date. Let's say if the launch_date is within 3 years from today's date, it should perform something but I only managed to come out with some portion of the code:
var today = new Date();
var launch_date = 2011/10/17 00:00:00 UTC;
//if today's date minus launch_date is within 3 years, then do something.
Any guides? Thanks in advance.
To explicitly check for the three year range
var ld = new Date('2011/10/17 00:00:00 UTC')
if(today.getFullYear() - ld.getFullYear() < 3) {
//do something
}
This will fail on an invalid date string and possibly some other edge cases.
If you'll be doing a lot of date calculations I highly recommend Moment: http://momentjs.com/
you could always calculate the timespan in days and use that.
var getDays = function(startDate, endDate){
var ONE_DAY = 1000 * 60 * 60 * 24;
var difference = endDate.getTime() - startDate.getTime();
return Math.round(difference / ONE_DAY);
}
See this JsFiddle: http://jsfiddle.net/bj4Dq/1/
Try-
var today = new Date();
var launch_date = new Date("2011/10/17 00:00:00 UTC");
var diff = today.getYear() - launch_date.getYear();
if(diff <=3 )
alert("yes");
else
alert("no");
jsFiddle
you can create a Date object and invoke getTime() method (returns numer of milliseconds since 1970-01-01). Use one of this rows:
var yourDate = new Date(dateString) // format yyyy-mm-dd hh:mm:ss
var yourDate = new Date(year, month, day, hours, minutes, seconds, milliseconds)
After in the if statement use this condition:
var edgeDate = // new Date(dateString);
if ( (today.getTime () - yourDate.getTime ()) >= edgeDate.getTime() ){
// do something
}
Regards,
Kevin

Using answers from prompt for a calculation

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

Categories

Resources