Store date in MongoDB without considering the time

2019-01-18 04:37发布

问题:

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?

回答1:

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.


回答2:

This means "you did it wrong". Good database practice has long been to store dates in UTC or Zulu time format. So what you should have done ( at least in JavaScript notation ) is this:

var  myDate = new Date ("2014-12-15");

And you should have considered that the date string you fed in was already converted from your local time to a UTC time, or just feed your object anyway since that is what the driver will do.

JavaScript has funny ways of interpreting the date "string" provided. So for example:

var  myDate = new Date ("2014/12/15");

Actually provides a date object in your "local" timezone to your application. Probably not what you really want in most circumstances.

Best Practice. Cannot emphasize that enough. The "universal time constant" is the only way you ever store date data. Otherwise you are doing it wrong.