Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store date in MongoDB without considering the timezone

Which is the best way to store a date in MongoDB without considering the timezone?

I try to explain the problem with an example:

Giuseppe in Italy created an invoce in date "December 15, 2014", when the system store this date, in MongoDB will be stored "2014-12-14T23:00:00.000Z".

John in UK read the invoice and see "December 14, 2014" as the invoice date.

Obviously this information is wrong becouse also Jhon should see "December 15, 2014" as the invoice date, how can I solve this problem?

like image 407
Giuseppe Santoro Avatar asked Dec 15 '14 11:12

Giuseppe Santoro


People also ask

Is datetime stored without timezone?

DATETIME is a date/time that does not store timezone. TIMESTAMP is a date/time that does store timezone.

Can we store date in MongoDB?

The DATE type in MongoDB can store date and time values as a combined unit. The BSON Date type is a signed 64-bit integer representing the number of milliseconds since the Unix epoch (Jan 1, 1970).

How should I store dates in MongoDB?

The best format to store date and time in MongoDB is native javascript Date() or ISO date format as it internally converts it into BSON native Date object.

Does MongoDB store date in UTC?

MongoDB stores times in UTC by default, and will convert any local time representations into this form. Applications that must operate or report on some unmodified local time value may store the time zone alongside the UTC timestamp, and compute the original local time in their application logic.


1 Answers

Whole dates should not be placed in a Date object. Despite the name, Date represents a date and a time. If the value you're working with represents a whole date, rather than a specific time on that date, then you should store the value in another format.

Options are:

  • A string in YYYY-MM-DD or YYYYMMDD format
  • An integer number of whole days since some reference point.
like image 161
Matt Johnson-Pint Avatar answered Sep 24 '22 22:09

Matt Johnson-Pint