FKM
FKM

Reputation: 143

Calculate time ago / days ago from javascript dates that had to be converted to string

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.

Upvotes: 0

Views: 1401

Answers (2)

Luis Paulo Pinto
Luis Paulo Pinto

Reputation: 6036

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

Upvotes: 1

Elias Schablowski
Elias Schablowski

Reputation: 2812

Although I would suggest keeping the original Date - or the unedited ISO string, you can parse the value (since it is an ISO String, all data is kept and we can reconstruct the original.

This little function can convert the strings back to Dates (note: this uses some ES6 features which are not strictly necessary but can be avoided in exchange for more verbose code)

const s = "20200805013945088";


function parseDate(s) {
  let t = [s.substr(0, 4)];
  for(let i = 0; i < 5; i++){
    t.push(s.substr(4 + (2 * i), 2))
  }
  t.push(s.substr(14));
  t = t.map((s)=>parseInt(s));
  return new Date(...t);
}

console.log(parseDate(s));

Upvotes: 1

Related Questions