Reputation: 47
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
Please how can I solve this issue?
Upvotes: 0
Views: 211
Reputation: 19
Here is few changes in your function:
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 = new Date(timeStamp).getDate();
month = new Date(timeStamp).toDateString().match(/ [a-zA-Z]*/)[0].replace(" ", "");
year = new Date(timeStamp).getFullYear() == now.getFullYear() ? "" : " " +
new Date(timeStamp).getFullYear();
return day + " " + month + year;
}
}
And use timestamp as integer:
const currentTimeStamp = 1659377138217;
Upvotes: 1
Reputation: 1596
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));
Upvotes: 1