i am making a project about daily newspaper for hotels. For example I want to display all activities in daily-newspaper tab on website, but also in homepage I want to display the close activites, for example if it’s last 2 hours for karaoke, i want to display it in homepage with ejsif. All datas are fake for project.
const dailyData = [
{id:1, name:"Yoga Lesson" ,time: "10:30 AM", place:"Show Lounge", date:"26.07"},
{id:2, name:"Zumba" ,time: "16:30 PM", place:"Pool Area", date:"28.07"},
{id:3, name:"Disco" ,time: "12:00 AM ", place:"Eclipse Bar", date:"30.07"},
]
app.use("/daily", function(req,res) {
res.render("daily", {
dailyData: dailyData
})
});
So data is ready to use it in ".ejs" file.
<ul>
<% dailyData.forEach(data => { %>
<% if (data.time < ("I need help here")) { %>
<% } %>
<% }) %>
</ul>
Here I don’t know with what I should compare the data.time. I want to display the data, if it’s closer than 2 hours.
Thank you.
2
Answers
Instead of having two different time properties, consider using Unix time. You can modify your dailyData objects to look something like this:
Beware that JS uses milliseconds instead of seconds, so you’ll have to multiply the time given you by some converters by 1000.
When it comes to rendering this, you can modify the format using
DateTimeFormat
, like this example:This makes comparing super easy.
This code creates a Date object for the current time
currentTime
and another Date object for the time of each activityactivityTime
. It calculates the difference between these two times in hourshoursDiff
. If this difference is less than or equal to 2, it displays the data.Also make sure that
data.time
is in24 hours
format for this to work correctly.this approach assumes the dates are for the current year. If that’s not the case, you may need to adjust the year in the activityTime creation accordingly.