Date()

  • Date()
  • Returns a date either as a string or as aDate object.

    • Date() returns the current date as a string in themongo shell.
    • new Date() returns the current date as aDate object. The mongo shellwraps the Date object with theISODate helper. The ISODate is in UTC.You can specify a particular date by passing an ISO-8601 date stringwith a year within the inclusive range 0 through 9999 to thenew Date() constructor or the ISODate() function. Thesefunctions accept the following formats:

    • new Date("<YYYY-mm-dd>") returns the ISODate with thespecified date.

    • new Date("<YYYY-mm-ddTHH:MM:ss>") specifies the datetimein the client’s local timezone and returns the ISODate with thespecified datetime in UTC.
    • new Date("<YYYY-mm-ddTHH:MM:ssZ>") specifies thedatetime in UTC and returns the ISODate with the specifieddatetime in UTC.
    • new Date(<integer>) specifies the datetime as millisecondssince the Unix epoch (Jan 1, 1970), and returns theresulting ISODate instance.

Behavior

Internally, Date objects are stored as a signed64-bit integer representing the number of milliseconds since the Unixepoch (Jan 1, 1970).

Not all database operations and drivers support the full 64-bit range.You may safely work with dates with years within the inclusive range0 through 9999.

Examples

Use Date in a Query

If no document with _id equal to 1 exists in the productscollection, the following operation inserts a document with the fielddateAdded set to the current date:

  1. db.products.update(
  2. { _id: 1 },
  3. {
  4. $set: { item: "apple" },
  5. $setOnInsert: { dateAdded: new Date() }
  6. },
  7. { upsert: true }
  8. )

See also

$currentDate

Return Date as a String

To return the date as a string, use the Date() method, as in thefollowing example:

  1. var myDateString = Date();

Return Date as Date Object

The mongo shell wrap objects ofDate type with the ISODate helper;however, the objects remain of type Date.

The following example uses new Date() to returnDate object with the specified UTC datetime.

  1. var myDate = new Date("2016-05-18T16:00:00Z");

See also

BSON Date, mongo ShellDate