Calculating a time interval between two dates might be challenging due to time conversion calculations in miliseconds. In this tutorial, you will learn how to get a time between two dates using Wix Velo code.
Below, there is a code snippet to retreive data from the collection specified "quotes" and calculate leadTime and deliveryTime before insert together with a function called calculateDays().
export function quotes_beforeInsert(item, context) {
item.leadTime = calculateDays(item, item.leadDate);
item.deliveryTime = calculateDays(item, item.deliveryDate);
return item;
}
function calculateDays(item, dateSpecificed) {
const createdDate = item._createdDate;
const microSecondsDiff = dateSpecificed.getTime() - createdDate.getTime();
const dayDiff = Math.ceil(microSecondsDiff / (1000 * 3600 * 24));
return dayDiff;
}
For now, you should pay attention to the calculateDays() function to understand how to find the time difference between two date values.
In order to calculate the difference, we first need to get the date data from an object. In this case, it is the data field from the Wix CMS.
The first date field is _createdDate and the second one is the one used as parameter inside beforeInsert hook, leadDate.
const createdDate = item._createdDate;
const microSecondsDiff = dateSpecificed.getTime() - createdDate.getTime();
const dayDiff = Math.ceil(microSecondsDiff / (1000 * 3600 * 24));
console.log("das diff: " + dayDiff);
return dayDiff;
We first need to get the time stamp for each date value so that we can calculate the time difference just by subsctracting the one from another.
getTime() gets the time stamp in miliseconds for each date.
After we find the time difference in miliseconds, we will then find that time difference in days by dividing our values with (1000*60*60*24).
// Number of milliseconds in a day:
// 24 hrs/day * 60 minutes/hour * 60 seconds/minute * 1000 msecs/second
Now, put the value you found into Math.ceil() to get the day difference.
You can weather use similar codes on backend files and page codes.
If you have further questions, you can ask in the comments. 😀
Hint: For minute difference, use the code below:
var minsDiff = Math.floor(microSecondsDiff / (1000 * 60));
console.log("minutes diff: " + minsDiff);