How to Format Time Since Xxx E.G. "4 Minutes Ago" Similar to Stack Exchange Sites

Format time in JS

I don't think there's an easy way to do this with Moment.js.

However, using Luxon (successor to Moment.js) you can create an interval, convert it to a duration then format the values. E.g. to get the years, months and days from the ECMAScript epoch to now:

// Create an interval from 1 Jan 1970 UTC to now
let interval = luxon.Interval.fromDateTimes(
new Date(0), // 1 Jan 1970 UTC
new Date() // now
);

// Show default interval object
console.log(interval.toFormat('yyyy-MM-dd'));

// Convert to duration object
let d = interval.toDuration(['years','months','days']).toObject();

// Display in friendly format
let text = [];
d.years? text.push(d.years + ' years') : null;
d.months? text.push(d.months + ' months') : null;
d.days? text.push(d.days.toFixed(1) + ' days') : null;

console.log(text.join(', '));
<script src="https://cdnjs.cloudflare.com/ajax/libs/luxon/2.3.0/luxon.min.js"></script>

How to format timestamp in JavaScript

EDIT:

Here is a version that does not rely on 3rd party plugins, as some people noted in the comments, Moment.js is now longer maintained, an modern date functions are able to handle this job pretty well on their own, although, of course, there might be some edge cases to be considered.

const date = new Date(Date.now() - 600000);
document.getElementById("date").value = `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()} ${date.getHours()}:${date.getMinutes()}`;

document.getElementById("calc").addEventListener("click", () => {
document.getElementById("output").textContent = getTimeMessage(document.getElementById("date").value);
});

getTimeMessage = (timeStamp) => {
const aMonths = ["January", "Februray", "March", "April", "Mai", "June", "Juli", "August", "September", "October", "November", "December"];
const now = new Date();
const messageTime = new Date(timeStamp);
const diff = (now - messageTime);
const aDiff = {
sec: parseInt(diff / 1000),
min: parseInt(diff / 1000 / 60),
h: parseInt(diff / 1000 / 60 / 60),
d: parseInt(diff / 1000 / 60 / 60 / 24)
};
const formatDayOfMonth = (day) => {
// borrowed from https://stackoverflow.com/a/18289487/13987708
const array = `${day}`.split("").reverse(); // E.g. 123 = array("3","2","1")
array[0] = +array[1] === 1 ? 0 : +array[0]; // Number is in the teens

switch (array[0]) {
case 1: return `${day}st`;
case 2: return `${day}nd`;
case 3: return `${day}rd`;
default: return `${day}th`;
}
};
const padNumber = (number) => {
return (number < 10) ? `0${number}` : number;
};
const formatHoursOfDay = (hour, militaryTime) => {
return padNumber(!militaryTime ? hour > 12 ? hour - 12 : hour : hour);
};
const formatedMonth = aMonths[messageTime.getMonth()];
const formatedDay = formatDayOfMonth(messageTime.getDate());
const formatedHours = formatHoursOfDay(messageTime.getHours(), true);
const formatedMinutes = padNumber(messageTime.getMinutes());
const timeString = `${formatedHours}:${formatedMinutes}`;
const dateString = `${formatedMonth} the ${formatedDay}`;

if (aDiff.min < 60) {
return `Message received ${aDiff.min} minutes ago`;
} else if (now.getDate() === messageTime.getDate() && aDiff.d <= 1) {
return `Message received today at ${timeString}`;
} else if ((now.getDate() - 1) === messageTime.getDate() && aDiff.d <= 2) {
return `Message received yesterday at ${timeString}`;
} else if (now.getFullYear() === messageTime.getFullYear()) {
return `Message received on ${dateString} at ${timeString}`;
} else {
return `Message received on ${dateString}, ${messageTime.getFullYear()} at ${timeString}`;
}
}
<label>
Massage Date:
<input type="text" id="date">
</label>
<button id="calc">Show Result</button>

<p id="output"></p>

Check if time in minutes since start of week is between two values (value in minutes since start of week) at different intervals

Using an offset from the start of Sunday doesn't seem like a good idea where daylight saving is observed. Most places use Sunday as the changeover day, so on those days Sunday isn't 24 hours long and all offsets for that week will be ± the DST shift in minutes.

Ignoring that issue, it's fairly simple to convert a date to an offset: subtract the previous Sunday and divide the difference by the milliseconds in one minute. Converting from an offset to Date is the opposite: add the minutes to a Date for the previous Sunday, e.g.

// Return Date for start of Sunday 00:00 before d
function startOfWeek(d = new Date()) {
return new Date(d.getFullYear(), d.getMonth(), d.getDate() - d.getDay());
}

// Convert a Date to an offset in minutes
// from start of previous Sunday
function dateToOffset(d = new Date()) {
return Math.floor((d - startOfWeek(d)) / 6e4);
}

// Convert an offset to date, default is current week
// Week starts on Sunday
function offsetToDate(offset, d = new Date()) {
let date = startOfWeek(d);
date.setMinutes(offset);
return date;
}

// Examples
// Just a helper to format dates
function format(d) {
return d.toLocaleString('en', {
weekday: 'short',
hour: '2-digit',
hour12: false,
minute: '2-digit'
});
}

// Show current offset
let d = new Date();
console.log(`For ${format(d)} the offset is ${dateToOffset(d)}`);

// Convert offsets to dates
let data = [
{ "start_time": 1980, "end_time": 2460 },
{ "start_time": 3420, "end_time": 3900 },
{ "start_time": 4860, "end_time": 5340 },
{ "start_time": 6300, "end_time": 6780 },
{ "start_time": 7740, "end_time": 8220 }
];
data.forEach(o => console.log(
`Start: ${format(offsetToDate(o.start_time))} ` +
`End : ${format(offsetToDate(o.end_time))}`
));

// Find out if dates are between a start and end
[new Date(2021,10,25,12), // Thu 25 Nov 12:00
new Date(2021,10,27,12), // Sat 25 Nov 12:00
new Date() // Now
].forEach(d => {
let offset = dateToOffset(d);
console.log(
`Is ${format(d)} between a start and end? ` +
`${!!data.find(obj => obj.start_time <= offset && obj.end_time > offset)? 'Yes' : 'No'}`
)
});

How can I calculate the differences between now date and constant date. And edit it like 1d,1m,1w

I would recommend moment.js to you moment.js docs - difference

const date1 = moment('2016-10-08 10:29:23');
const date2 = moment('2016-10-08 11:06:55');
const diff = date2.diff(date1);
const minutesDif= date2.diff(date1, 'minutes');

for your exact application i would recommend a look into the documentation



Related Topics



Leave a reply



Submit