I show date by this in ejs
<%= new Date();%>
it give me result
Tue Feb 02 2016 16:02:24 GMT+0530 (IST)
You don't need moment js, you can simply use this
<%= new Date().getFullYear();%>
You can use moment
In your controller,
var moment = require('moment');
exports.index = function(req, res) {
res.render('index', { moment: moment });
}
In your html,
<html>
<h1><%= moment().format('Do MMMM, YYYY'); %></h1>
</html>
If you can live without ordinal day (th, nd, rd etc) you could use basic JS
<%= new Intl.DateTimeFormat('en-GB', { year: 'numeric', month: 'long', day: '2-digit'}).format(new Date()) %>
// Expected output: 25 August 2020
Post is old but in case anyone runs into the issue.
You can eliminate installing moment and write one little line of code. adding .toDateString() will provide you with the above format in ejs.
however, Moment is used for more detailed date, such as Day, or month or year etc...
The problem with most of the answers on this page is that they will format the date using the server's locale, but you probably want them rendered in the user's locale. For example, if your server is in Virginia, your dates will be displayed in English in Eastern Time, but a user in another country will probably want them displayed differently.
The following code snippet will render date
using the user's locale. There's room for improvement, but it's a starting point:
<p>
<script type="text/javascript">
document.write(
new Date("<%= date.toISOString() %>").toLocaleDateString()
);
</script>
</p>
This takes the date on the server, converts it to an ISO-8601 string, and interpolates it into a little JavaScript snippet that runs client-side to produce the correct localized output.
For more information on toLocaleString, see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString
You can do this:
<%= moment(user.date).format( 'MMM-DD-YYYY') %>
For a better code management, you can add the code(below) in app.js/server.js. This will save moment
in the res.locals.moment
at the time of starting the app. By doing this you can access the moment
variable from any ejs page.
app.js/server.js:
const express = require("express");
const app = express();
const moment = require("moment");
app.use((req, res, next)=>{
res.locals.moment = moment;
next();
});
something.ejs
<p><%= moment(yourDateVariable).format('Do MMMM, YYYY') %></p>
Here Do
will result with 19th
.You can check it here https://momentjs.com/docs/#/displaying/format/. Hope this will help.