Datetime formatting / customization in ejs
Asked Answered
ejs
P

9

28

I show date by this in ejs

<%= new Date();%>

it give me result

Tue Feb 02 2016 16:02:24 GMT+0530 (IST)

But I need to show as

19th January, 2016

How can I do this in ejs?

Pettifog answered 2/2, 2016 at 10:41 Comment(1)
Note: The way you display a date differs from user to user and country to country. See my answer below for more information.Galliot
T
38

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>

EDIT :

Using basic JS

const suffixMap = {
  one: 'st',
  two: 'nd',
  few: 'rd',
  other: 'th',
};

const date = new Date();
const dateDay = date.getDate();
const dateMonth = date.toLocaleString('default', {month: 'long'});
const dateYear = date.getFullYear();
const pluralRule = new Intl.PluralRules('en-GB', {type: 'ordinal'});
const dateOrdinal = suffixMap[pluralRule.select(dateDay)]

const ordinalDateString = `${dateDay}${dateOrdinal} ${dateMonth}, ${dateYear}`; 
// Expected output: 25th August, 2020

(Adapted from this answer)

const date = new Date();
const dateDay = date.getDate();
const dateMonth = date.toLocaleString('default', {month: 'long'});
const dateYear = date.getFullYear();

// DETERMINE DATE ORDINAL
let dateOrdinal = 'th';

dateOrdinal = ([1, 21, 31].indexOf(dateDay) > -1) ? 'st' : dateOrdinal;
dateOrdinal = ([2, 22].indexOf(dateDay) > -1) ? 'nd' : dateOrdinal;
dateOrdinal = ([3, 23].indexOf(dateDay) > -1) ? 'rd' : dateOrdinal;

// FORMAT DATE AS STRING
const ordinalDateString = `${dateDay}${dateOrdinal} ${dateMonth}, ${dateYear}`; 
// Expected output: 25th August, 2020

Or, 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
Turnsole answered 2/2, 2016 at 10:58 Comment(0)
V
20

You don't need moment js, you can simply use this

<%= new Date().getFullYear();%>

Veteran answered 22/8, 2018 at 12:40 Comment(0)
W
10

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

Wendolyn answered 15/3, 2018 at 20:42 Comment(0)
L
4

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.

Lactalbumin answered 29/4, 2020 at 14:16 Comment(0)
U
1

You can do this:

<%= moment(user.date).format( 'MMM-DD-YYYY') %>
Utopian answered 19/5, 2017 at 2:49 Comment(1)
If you add moment as a js script you can't because moment is not defined when the page is rendering. You have to pass moment to the .ejs file like the most upvoted answer.Duodenal
G
1

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

Galliot answered 5/2, 2021 at 22:6 Comment(1)
If you're going to do this, you should probably avoid document.write and use .innerText insteadMarathi
S
1
// I have tested this in a for loop, it seems to be ok.

<% let d = new Date(); %>
<% let day = d.getDate(); %>
<% let m = ["January", "February", "March", "April", "May", "June", "July", 
"August", "September", "October", "November", "December"]; %>
<% let month = m[d.getMonth()]; %>
<% let year = d.getFullYear(); %>
<% let newdate = day + "th " + month + ", " + year; %>
<%= newdate %> // 22th July, 2022

// You can use the if...else statement for the ordinal number
Singband answered 21/7, 2022 at 16:16 Comment(0)
E
1
 <h1>
  <%= new Date().getDate() %> <%= new Date().toLocaleString('default', {month: 'long'});  %>,<%= new Date().getFullYear();  %>
</h1>
Erudition answered 12/8, 2023 at 18:46 Comment(1)
This gives the output like "13 August,2023".Nothing new just after refering all the above answers this is the simplified answerErudition
C
0

My use case required populating the post's createdAt time to a HTML file in a human readable format. Here is a sample code snippet without using the moment.js

<h6 class="text-xs text-zinc-600"><%= post.createdAt.toDateString() %></h6>
Combust answered 23/6 at 23:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.