Skip to content
Advertisement

How to format datetime in EJS?

enter image description here

I am trying to achieve the datetime format like this 1:00 am May 11 2020? I am using mongoDB and EJS

How can I do it in my code?

Here is my server.js code:

// Import
const express = require('express')
const mongoose = require('mongoose');

const app = express();

mongoose.connect('mongodb://localhost/name_of_your_DB', {
    useNewUrlParser: true
});

const UserSchema = new mongoose.Schema({
    name: {
        type: String
    },
    quote: {
        type: String
    },
    created_at: {
        type: Date,
        default: Date.now
    }
})
// Create an object that contains methods for mongoose to interface with MongoDB
const User = mongoose.model('User', UserSchema);

// Setting
app.use(express.static(__dirname + '/static'))
app.set('view engine', 'ejs')
app.set('views', __dirname + '/views')

app.use(express.json())
app.use(express.urlencoded({
    extended: true
}))

// Routes
app.get('/', (req, res) => {
    res.render('index')
});



app.post('/process', (req, res) => {
    const user = new User();
    user.name = req.body.name
    user.quote = req.body.quote
    user.save()
        .catch(err => {
            console.log('Error saving user:', err)
        })
    res.redirect('/quotes')
})


app.get('/quotes', (req, res) => {
    User.find({}, (err, quotes) => {
        var context = {
            quotes: quotes
        };

        if (err) {
            console.log('Something went wrong')
        }

        res.render("quotes", context);
    });
});

app.get('/delete', (req, res) => {
    User.remove({})
        .then(data => {
            res.json(data)
        })
    res.redirect('/quotes');
})

app.listen(8000)

And here’s my EJS template:

    <div class="container bg-light" id="quote">
        <h2>Here are the awesome quotes!</h2>
        <div class="quote clearfix">
            <% for (var user in quotes) { %>
            <p class="quote"><b> "<%= quotes[user].quote %>"</b></p>
            <p class="date"> - "<%= quotes[user].name %>" at <%= quotes[user].created_at %></p>
            <hr>
            <% } %>
            <div class="row">
                <a href="/" class="col">
                    <button class="btn btn-primary">Go back</button>
                </a>
                <a href="/delete" class="col">
                    <button class="btn btn-danger float-right" id="delete">Delete</button>
                </a></div>
        </div>
    </div>

How can can I achieve that format in my code??????????? I appreciate all the answers thank you so much! sdfdsfdsfdsf

Advertisement

Answer

Take a look at moment.js
To be able to use the moment npm module in ejs template, change the context variable:

var context = {
   quotes: quotes,
   moment: moment
};

Alternatively you can include Moment.js cdn script in the ejs template.

Then in your template, replace the corresponding ejs block with:
<%= moment(quotes[user].created_at).format('hh:mm a MMM DD YYYY') %>

Also check this out: How to format a JavaScript date

Advertisement