Asool Asool -4 years ago 197
Javascript Question

How to get date from mongoDB and display it, using moment.js?

I have a form where the user inputs the date in the following format: YYYY-MM-DD

I store the date in Mongo DB. By default, Mongo DB stores it as a UTC Date.

User inputs 2018-02-06
Mongo stores: "Tue Feb 06 2018 00:00:00 GMT+0000 (UTC)"

Lets say I want to display this date back to the user.

The following code gives me the wrong date:

var eventDateString = $('#hiddenDate').val() // Just gets the date as stored in mongo
var dateObj = new Date(eventDateString)
var dateMom = moment(dateObj).format('dddd, MMMM DD YYYY');

What gets printed is:
"Monday, February 05 2018"
This is incorrect, the date should be Feb 6.

Why is this happening?

I tried to solve the issue by doing this:

var eventDateString = $('#hiddenDate').val();
$('#show-eventDate').text(moment.utc(eventDateString).format('dddd, MMMM DD YYYY'));

I get the correct Result: "Tuesday, February 06 2018"

However, I get the following warning:

enter image description here

(Deprecation warning: value provided is not in a recognized ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non ISO date formats are discouraged and will be removed in an upcoming major release. Please refer to for more info....)

How do I get around this issue?

Answer Source

So I did this to avoid the depreciation warning, and it worked

var eventDateString = $('#hiddenDate').val();
var index = eventDateString.indexOf('00:00');
var shortDate = eventDateString.substr(0,index-1);
$('#show-eventDate').text(moment(shortDate, 'ddd MMM DD YYYY').format('dddd, MMMM DD YYYY'));

But I don't like the idea that I'm hardcoding '00:00' -- any better solution would be appreciated

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download