Reputation: 107
How to use moment.js correctly? I want to save a created
date to mongoDB using a form? I am currently using:
var blogSchema = new mongoose.Schema({
title: String,
image: String,
body: String,
created: {type: Date, default: Date.now}
});
When displaying the date on the blog post, I then use the following to convert it to a more readable format:
<span class="inline-block"><%= blog.created.toDateString() %></span>
How to display the current date as "DD-MM-YYYY @ mm:hh"
when submitting the post?
Upvotes: 0
Views: 1387
Reputation: 107
I don't think I was very clear when explaining what I was trying to do. I wanted to use moment to convert a date in a .ejs template. The solution was to use:
app.locals.moment = require("moment");
in the app.js file and then use:
<span><%= moment(blog.created).fromNow() %></span>
Which gave the following rendered result:
Upvotes: 0
Reputation: 5041
You have two options.
Get access to momentjs from your ejs file and then simply do:
<%= moment(yourDateVariable).format('DD-MM-YYYY') %>
Give format to the date before passing the data to your ejs.
yourDateVariable = moment(yourDateVariable).format('DD-MM-YYYY');
return res.render('yourView', {yourDateVariable});
Upvotes: 0
Reputation: 563
Assuming that the date value you get from mongodb is a timestamp value:
Then you can use moment.js like this:
var timeValueFromMongoDB = 1515089852632;
var result = moment(timeValueFromMongoDB).format('DD-MM-YYYY @ mm:hh');
// Use this output to display wherever you want
04-01-2018 @ 17:01
Jsfiddle example http://jsfiddle.net/rLjQx/5208/
Upvotes: 2