Due to limitations with next js, data could not be passed to client without being converted to string.
So date obtaned from database is is now a string:
Past date as string is: 20200802016944990
I use new Date() to get the current date and convert it to string as well (Notice T is missing from my string date)
Present date as string is: 20200805013945088
In both cases, I the code below to convert to string
.toISOString().replace(/[^0-9]/g, "");
If these were not strings, its simple as date1 – date 2.
How to get mins/ hours/ days ago from past date and present date which are now strings?
I am using React js and Next js. I do not want to install a library like moment js.
Advertisement
Answer
Another approach is instead convert it to ISOstring, would be convert it to milliseconds with getTime() (it returns a number), and then would be easir to recover date and get the info you want (day, hours, minutes, etc..)
const dbDate = new Date().getTime();
console.log('getTime value =>', dbDate);
const parsedDate = new Date(dbDate);
console.log('parsed date =>', parsedDate);
console.log('Date =>', parsedDate .getDate());
console.log('Hours =>', parsedDate .getHours());
console.log('Minutes =>', parsedDate .getMinutes());
//Once you get the dates, you can do the date calculate, like:
//Get 1 day in milliseconds
var one_day=1000*60*60*24;
const date1 = new Date('9/9/2020').getTime(); //JUST AN EXAMPLE
const date2 = new Date('10/9/2020').getTime(); //JUST AN EXAMPLE
const diffTime = Math.abs(date2 - date1);
const diffDays = Math.ceil(diffTime / one_day);
console.log(diffTime + " milliseconds");
console.log(diffDays + " days");