ac360
ac360

Reputation: 7835

Why Does MongoDB Say I have an Invalid Date? / More Confusion With Javascript Dates

I admit I'm having a hard time understanding javascript dates and timezone conversions. Server side, in my node app, I'm trying to convert price/date data that only ever deals in MST timezone to javascript date objects, and save them to the database. Under no circumstances, server-side or client-side, do I ever want to convert the dates into any other timezone. I have this working except for one date in particular says Invalid Date when it is fetched from my mongodb database...

This is the original data that I need to reformat. It states the day and the hour the price was set...

02/17/2014 24

Effectively, this is 12:00AM on 02/18/2014, so I need to create that date object and save it into mongodb. Now, these prices are set on an exchange in a fixed timezone and I don't want any timezone conversions for any reason, but I kept getting them when I created my date object, so this is what I finally settled on. A combo of Javascript Date Objects and Moment.js help...

 if (hour === "24") {
       date = new Date(day+" 00:00:00");
       date.setDate(date.getDate() + 1);
       date = moment.tz(date, 'America/Phoenix').format("YYYY-MM-DDTHH:mm:ss");
 } else {
       date = new Date(full_date + ":00:00");
       date = moment.tz(date, 'America/Phoenix').format("YYYY-MM-DDTHH:mm:ss");
 };

And then I save that date into mongodb in a Date type property of my model...

This works for hours 1 - 23, but when I fetch data from my database from hour 24, it always returns Invalid Date

Upvotes: 0

Views: 1244

Answers (1)

Stennie
Stennie

Reputation: 65363

The day, month, hours, minutes, and seconds components in JavaScript dates are 0-based, so the range of values for "day" should be 0-23.

Since you are using moment.tz, it would be more straightforward to construct your dates by passing an ISO date string and doing the date math using moment.

Here are a few different ways to represent midnight on Feb 18th, 2014 with moment.tz:

> moment("2014-02-17").tz("America/Phoenix").add('days', 1).format()
'2014-02-17T06:00:00-07:00'

> moment("2014-02-18").tz("America/Phoenix").format()
'2014-02-17T06:00:00-07:00'

> moment("2014-02-18 0:00").tz("America/Phoenix").format()
'2014-02-17T06:00:00-07:00'

Upvotes: 1

Related Questions