Data formatting in Node.JS, with Sequelize and Moment.JS

Asked

Viewed 383 times

0

I would like to format a date that is being loaded from the database with Sequelize. I’m blogging and I need to get the article creation date

My route:

app.get("/", (req,res) =>{
    Article.findAll({
        order:[
            ['id','DESC']
        ],
        limit:6
    }).then(articles =>{
        Category.findAll().then(categories =>{
            res.render("index.ejs", {articles:articles, categories:categories})
        })
    })
})

In my "INDEX.EJS", I am foreach the articles:

        <% articles.forEach(articles => {%>
    <div class="card">
        <div class="card-header">
            <h2><%= articles.title%></h2>
            
        </div>
        <br>
        <div class="card-body" >
            <%- articles.img%>
            <h5><%= articles.subtitle%></h5>
            <h5 id="displayMoment"><%= articles.createdAt%></h5>
            <a href="/<%= articles.slug%>" class="btn btn-success">Ler artigo</a>
        </div>
    </div>
    <br>
<% })%>

<script type="text/javascript">
(function()
{
  var NowMoment = moment().format('LLL');

  var eDisplayMoment = document.getElementById('displayMoment');
  eDisplayMoment.innerHTML = NowMoment;  
})();
</script>

It is returning the current date, not the creation date of the articles. I would more like to know how you pass this createdAt variable inside the Moment()

1 answer

0

The problem is you’re using moment().

To format the project creation date, you need to inform it to Moment using the parameter.

For example:

(function()
{
  var NowMoment = moment("<%= articles.createdAt %>").format('LLL');

  var eDisplayMoment = document.getElementById('displayMoment');
  eDisplayMoment.innerHTML = NowMoment;  
})();
  • I already tried to do this, but it returns as invalid date

Browser other questions tagged

You are not signed in. Login or sign up in order to post.