'How do I format dates from Mongoose in Node.js?
I'm trying to change the format of the dates I'm getting from my Mongo database. Currently they look like this:
Fri Sep 16 2011 19:05:17 GMT+0900 (JST)
I've tried calling .toString('yyyy-MM-dd') on them but nothing changes. I don't know if they're Date objects or just raw strings.
I've tried checking the Mongoose manual and googling a bunch, but not found anything yet.
Any ideas?
Solution 1:[1]
A modern way to do this is to use momentjs, both usable in node and in the browser, super useful and simple to use. For the current problem I solved it like this in node after following all the docs requirements :
var moment = require('moment');
var fomatted_date = moment(photo.date_published).format('YYYY-MM-DD');
with photo.date_published directly coming from mongoose.
Solution 2:[2]
what about defining your schema like:
var someSchema = new Schema({
title: String,
created: Date
});
s.t. the date is stored as a Date object in your mongoDB. As a result, when you read it back you'll have a proper Date object on which you can work with the available methods.
Solution 3:[3]
Just Simply Add
date: { type: String, default: Date }
Output will be: { "date": "Sat Nov 28 2020 22:57:38 GMT+0530 (India Standard Time)" }
Solution 4:[4]
created_at:{ type:Date, default:Date.now } add this simple line for current date and time
output:----- Fri Jul 02 2021 10:45:26 GMT+0530 (India Standard Time)
Solution 5:[5]
What I tend to do is, in the Schema, I define dates with a Date type:
const exampleSchema = new mongoose.Schema({
startDate: {
type: Date,
required: true // or false, depending upon needs (plus other options, as needed)
},
endDate: {
type: Date,
required: true // or false, depending upon needs (plus other options, as needed)
},
whateverDate: {
type: Date,
required: true // or false, depending upon needs (plus other options, as needed)
}
});
Then I define an instance method for the mongoose schema:
// Returns a date in 'yyyy-MM-dd' format
exampleSchema.methods.formatDate = function(datePropery) {
const newDate = new Date(this[dateProperty]);
let formattedDate = `${ newDate.getFullYear() }-`;
formattedDate += `${ `0${ newDate.getMonth() + 1 }`.slice(-2) }-`; // for double digit month
formattedDate += `${ `0${ newDate.getDate() }`.slice(-2) }`; // for double digit day
return formattedDate;
}
And, define the mongoose model:
const Example = new mongoose.model('Example', exampleSchema);
Later, after I've selected a particular instance (for me this is generally within an async function), e.g.
const item = await Example.findOne({searchFor: searchTerm});
I can get the formatted dates in the following way:
item.formatDate('startDate'); // for startDate field (see exampleSchema), or
item.formatDate('endDate'); // for endDate field (see exampleSchema), or
item.formatDate('whateverDate'); // for whateverDate field (see exampleSchema).
If the item is passed from Express to HTML, e.g.:
res.render('mypage', {item});
it can then be used in HTML (at least for the case of ejs view engine) as:
<%= item.formatDate('startDate') %>
<%= item.formatDate('endDate') %>
<%= item.formatDate('whateverDate') %>
Perhaps this is a bit long-winded, although it works nicely for me.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Simon |
| Solution 2 | Juri |
| Solution 3 | Nishant Rana |
| Solution 4 | tarun rathore |
| Solution 5 | Atif |
