Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to resolve timeStamp.getDate is not a function

So I am trying to use Javascript timestamp to relative time, So I stumbled onto this code below, which helps.

function timeSince(timeStamp){
    var now = new Date(),
      secondsPast = (now.getTime() - timeStamp) / 1000;
    if (secondsPast < 60) {
      return parseInt(secondsPast) + 's';
    }
    if (secondsPast < 3600) {
      return parseInt(secondsPast / 60) + 'm';
    }
    if (secondsPast <= 86400) {
      return parseInt(secondsPast / 3600) + 'h';
    }
    if (secondsPast > 86400) {
      day = timeStamp.getDate();
      month = timeStamp.toDateString().match(/ [a-zA-Z]*/)[0].replace(" ", "");
      year = timeStamp.getFullYear() == now.getFullYear() ? "" : " " + 
      timeStamp.getFullYear();
      return day + " " + month + year;
    }
  }

const currentTimeStamp = new Date().getTime();
console.log(timeSince(currentTimeStamp));

But when am having a timeStamp more than 24hours or a timestamp like this

const currentTimeStamp = '1659377138217';
console.log(timeSince(currentTimeStamp));

It throws an error showing TypeError: timeStamp.getDate is not a function

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Please how can I solve this issue?

>Solution :

const currentTimeStamp = '1659377138217';
console.log(timeSince(currentTimeStamp));

currentTimeStamp is a string here, it must be converted to a date object to access date methods such as getDate(), try this:

const currentTimeStamp = new Date(parseInt('1659377138217'));
console.log(timeSince(currentTimeStamp));
1 comments

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading