Rate this quickstart
Dates and times in programming can be a challenge. Which Time Zone is the event happening in? What date format is being used? Is it
DD/MM/YYYY? Settling on a standard is important for data storage and then again when displaying the date and time. The recommended way to store dates in MongoDB is to use the BSON Date data type.
The refers to the
Datetype as the UTC datetime and is a 64-bit integer. It represents the number of milliseconds since the , which was 00:00:00 UTC on 1 January 1970. This provides a lot of flexibilty in past and future dates. With a 64-bit integer in use, we are able to represent dates roughly 290 million years before and after the epoch. As a signed 64-bit integer we are able to represent dates prior to 1 Jan 1970 with a negative number and positive numbers represent dates after 1 Jan 1970.
You'll want to use the
Datedata type whenever you need to store date and/or time values in MongoDB. You may have seen a
timestampdata type as well and thought "Oh, that's what I need." However, the
timestampdata type should be left for internal usage in MongoDB. The
Datetype is the data type we'll want to use for application development.
There are some benefits to using the
Datedata type in that it comes with some handy features and methods. Need to assign a
Datetype to a variable? We have you covered there:
What did that create exactly?
Very nice, we have a date and time wrapped as an ISODate. If we need that printed in a
stringformat, we can use the
datefield is the recommended data type to use when you want to store date and time information in MongoDB. It provides the flexibility to store date and time values in a consistent format that can easily be stored and retrieved by your application. Give the BSON
Datedata type a try for your applications.