JavaScript Timestamp to Relative Time

Javascript timestamp to relative time

Well it's pretty easy if you aren't overly concerned with accuracy. What wrong with the trivial method?

function timeDifference(current, previous) {

var msPerMinute = 60 * 1000;
var msPerHour = msPerMinute * 60;
var msPerDay = msPerHour * 24;
var msPerMonth = msPerDay * 30;
var msPerYear = msPerDay * 365;

var elapsed = current - previous;

if (elapsed < msPerMinute) {
return Math.round(elapsed/1000) + ' seconds ago';
}

else if (elapsed < msPerHour) {
return Math.round(elapsed/msPerMinute) + ' minutes ago';
}

else if (elapsed < msPerDay ) {
return Math.round(elapsed/msPerHour ) + ' hours ago';
}

else if (elapsed < msPerMonth) {
return 'approximately ' + Math.round(elapsed/msPerDay) + ' days ago';
}

else if (elapsed < msPerYear) {
return 'approximately ' + Math.round(elapsed/msPerMonth) + ' months ago';
}

else {
return 'approximately ' + Math.round(elapsed/msPerYear ) + ' years ago';
}
}

Working example here.

You might want to tweak it to handle the singular values better (e.g. 1 day instead of 1 days) if that bothers you.

Convert a Unix timestamp to time in JavaScript

let unix_timestamp = 1549312452// Create a new JavaScript Date object based on the timestamp// multiplied by 1000 so that the argument is in milliseconds, not seconds.var date = new Date(unix_timestamp * 1000);// Hours part from the timestampvar hours = date.getHours();// Minutes part from the timestampvar minutes = "0" + date.getMinutes();// Seconds part from the timestampvar seconds = "0" + date.getSeconds();
// Will display time in 10:30:23 formatvar formattedTime = hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);
console.log(formattedTime);

Javascript relative time 24 hours ago etc as time

You should use timestamps as you can calculate with them.

This is how you get the current timestamp: Math.round(new Date().getTime() / 1000)
Please note that this the computers local time.

Now you can get the timestamp 24 hours ago like this:

var ts = Math.round(new Date().getTime() / 1000);
var tsYesterday = ts - (24 * 3600);

Please see this fiddle: http://jsfiddle.net/Mjm7V/

Edit:
As Nick correctly pointed out, Date#getTime returns the UTC timestamp (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getTime)

React displaying relative time with javascript

This doesn't directly answer your question, but you really may want to consider moment for handling dates and times. Using moment or a similar library, you could replace your function with:

moment(previousDate).fromNow();

EDIT: If you can't use a library, I'd recommend as in my comment to convert everything to a numeric Unix timestamp to make the math much simpler. Here's a version assuming the incoming date has already been converted with getTime() or valueOf():

const timeAgo = (prevDate) => {
const diff = Number(new Date()) - prevDate;
const minute = 60 * 1000;
const hour = minute * 60;
const day = hour * 24;
const month = day * 30;
const year = day * 365;
switch (true) {
case diff < minute:
const seconds = Math.round(diff / 1000);
return `${seconds} ${seconds > 1 ? 'seconds' : 'second'} ago`
case diff < hour:
return Math.round(diff / minute) + ' minutes ago';
case diff < day:
return Math.round(diff / hour) + ' hours ago';
case diff < month:
return Math.round(diff / day) + ' days ago';
case diff < year:
return Math.round(diff / month) + ' months ago';
case diff > year:
return Math.round(diff / year) + ' years ago';
default:
return "";
}
};

...

console.log(timeAgo(new Date("Thu Oct 25 2018").getTime()));

I didn't do the singular/plural handling for all the units but you get the idea. It's just pure arithmetic if you convert your dates before you bring them into the function, which can be done easily with built-in JS functionality. You can even convert them inside the function if you know the format they're coming in as.

How to make a relative timestamp using ms (Or any other way), Discord.js

You just had to define a function that took a timestamp parameter and we had to divide it by 1000 to convert ms to seconds.
Let's say you took a current timestamp + add 30mins to it and feed it to the function, it will return the discord Embeddable countdown timer for 30mins.

const getCDStamp = (timestamp = Date.now()) => `<t:${Math.round(timestamp / 1000)}:R>`;

Full Code: https://sourceb.in/ki3jQuUXwe

Converting a timestamp to relative time

This function will return time same as Facebook:

public static String getTimeAgo(long time) {

final DateFormat sdfTime = new SimpleDateFormat("h:mm aa", Locale.ENGLISH);
final DateFormat sdf = new SimpleDateFormat("d MMM 'at' h:mm aa", Locale.ENGLISH);
final DateFormat sdfY = new SimpleDateFormat("d MMM yyyy 'at' h:mm aa", Locale.ENGLISH);

final int SECOND_MILLIS = 1000;
final int MINUTE_MILLIS = 60 * SECOND_MILLIS;
final int HOUR_MILLIS = 60 * MINUTE_MILLIS;
final int DAY_MILLIS = 24 * HOUR_MILLIS;

if (time < 1000000000000L) {
time *= 1000;
}

Calendar today = Calendar.getInstance();

Calendar timeCal = Calendar.getInstance();
timeCal.setTimeInMillis(time);

long now = System.currentTimeMillis();
if (time > now || time <= 0) {
return null;
}

final long diff = now - time;
if (diff < MINUTE_MILLIS) {
return "Just now";
} else if (diff < 2 * MINUTE_MILLIS) {
return "1 min";
} else if (diff < 59 * MINUTE_MILLIS) {
return diff / MINUTE_MILLIS + " mins";
} else if (diff < 2 * HOUR_MILLIS) {
return "1 hr";
} else if (diff < 24 * HOUR_MILLIS) {
return diff / HOUR_MILLIS + " hrs";
} else if (diff < 48 * HOUR_MILLIS) {
return ("Yesterday at " + capsAMtoSmall(sdfTime.format(timeCal.getTime())));
} else if (today.get(Calendar.YEAR) == timeCal.get(Calendar.YEAR)) {
return capsAMtoSmall(sdf.format(timeCal.getTime()));
} else {
return capsAMtoSmall(sdfY.format(timeCal.getTime()));
}
}


private static String capsAMtoSmall(String time) {
return time.replace("AM", "am").replace("PM","pm");
}

Happy coding :)



Related Topics



Leave a reply



Submit