I'm trying to find the date and time difference between two dates (and times). I'm trying to implement a countdown (to the event date) feature but coming across issues with my approach.
Note: Some of the variables defined below are in HuBL, HuBL can be used in Javascript so as long as they're in the same file.
Here's my current approach:
1. How I'm obtaining the data and time
In HubSpot, I have a database table. Within that table, I have a column which is of type date and time. For reference, the value in this field is the following:
I've ran a for loop to obtain its date and time as separate variables (event_date is the column name in the database table):
{% for data in table_query %}
{% set event_date = data.event_date|datetimeformat('%B %e, %Y') %}
{% set event_time = data.event_date|datetimeformat('%H %M') %}
{% endfor %}
To see the datetimeformat parameters I've used - see the documentation here
Doing {{ event_date }} prints: September 7, 2020
Doing {{ event_time }} prints: 11 59
2. Now that I have the date and time in vars, how I'm trying to find the difference
In hero.html:
{% for data in table_query %}
{% set event_date = data.event_date|datetimeformat('%B %e, %Y') %}
{% set event_time = data.event_date|datetimeformat('%H %M') %}
{% endfor %}
<script>
var event_date = new Date('{{ event_date }}');
var todays_date = new Date();
function getDifferenceInDays(event_date, todays_date) {
var diffInMs = Math.abs(todays_date - event_date);
return diffInMs / (1000 * 60 * 60 * 24);
}
function getDifferenceInHours(event_date, todays_date) {
var diffInMs = Math.abs(todays_date - event_date);
return diffInMs / (1000 * 60 * 60);
}
function getDifferenceInMinutes(event_date, todays_date) {
var diffInMs = Math.abs(todays_date - event_date);
return diffInMs / (1000 * 60);
}
function getDifferenceInSeconds(event_date, todays_date) {
var diffInMs = Math.abs(todays_date - event_date);
return diffInMs / 1000;
}
console.log(getDifferenceInDays(event_date, todays_date));
</script>
My issues:
With the above, I'm getting a console.log of NaN. I'm trying to get the results in days, hours, minutes, seconds because I'm dividing it for the countdown to event timer.
I'm am totally lost on how will be able to check against the event time - trying to get the countdown timer as accurate as possible, to countdown to event start, but unsure on how I can do this
Note: Tagging twig too as syntax is similar to HubL

Your problem is in event_data. you are getting maybe string beside integer. for example, if you hardcoded the new date you will get an answer to the console.
https://codepen.io/Elnatan/pen/jOqNPMm
(check the console)