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,
// 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')

    extended: true

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

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) => {
        .then(data => {


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>
            <% } %>
            <div class="row">
                <a href="/" class="col">
                    <button class="btn btn-primary">Go back</button>
                <a href="/delete" class="col">
                    <button class="btn btn-danger float-right" id="delete">Delete</button>

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


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

Answered By – Kashinath Patekar

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published