Search code examples
javascriptnode.jsdatetimenode-modulesejs

I want to add a real time to my node.js project and i want to use it in if-else situation


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 data is 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.


Solution

  • Instead of having two different time properties, consider using Unix time. You can modify your dailyData objects to look something like this:

    {id:1, name:"Yoga Lesson", time: 1690392600000, place:"Show Lounge"}
    

    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:

    date = data.time;
    options = {
      hour: "numeric",
      minute: "numeric",
      timeZone: "Australia/Sydney",
    };
    console.log(new Intl.DateTimeFormat("en-AU", options).format(date));
    

    This makes comparing super easy.

    if (date >= Date.now() && date <= Date.now() + 7200000) {
      console.log("Within two hours from now!");
    } else { console.log("Not within two hours from now."); }