Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 350
benui Avatar asked Sep 16 '11 10:09

benui


People also ask

What is the format for Date in Mongoose?

format('YYYY-MM-DD');

How can I format a Date coming from MongoDB?

You can specify a particular date by passing an ISO-8601 date string with a year within the inclusive range 0 through 9999 to the new Date() constructor or the ISODate() function. These functions accept the following formats: new Date("<YYYY-mm-dd>") returns the ISODate with the specified date.


2 Answers

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.

like image 131
eloone Avatar answered Sep 28 '22 04:09

eloone


you have to create a Date object first:

var date = new Date(dateStr);  // dateStr you get from mongodb

var d = date.getDate();
var m = date.getMonth()+1;
// ...
like image 21
Philipp Kyeck Avatar answered Sep 28 '22 03:09

Philipp Kyeck