To get the relative time 24 hours ago using JavaScript, you can create a new Date object for the current time and then subtract 24 hours from it.
To do this, we can write
// Get the current time
var currentTime = new Date();
// Subtract 24 hours (24 * 60 * 60 * 1000 milliseconds)
var twentyFourHoursAgo = new Date(currentTime - 24 * 60 * 60 * 1000);
// Format the date to display
var formattedTime = twentyFourHoursAgo.toLocaleString();
console.log("24 hours ago:", formattedTime);
In this code, we create a new Date
object called currentTime
, representing the current time.
We then subtract 24 hours from currentTime
by creating a new Date
object called twentyFourHoursAgo
using the milliseconds equivalent of 24 hours.
Finally, we format the twentyFourHoursAgo
date object into a human-readable string using the toLocaleString()
method.
This will give you the date and time 24 hours ago relative to the current time. You can adjust the formatting to suit your needs.