Current epoch — epochtime.tools · A precision instrument for time

Get the current Unix timestamp

// mongosh
Date.now()                       // ms
Math.floor(Date.now() / 1000)    // s
// In an aggregation pipeline the current time is "$$NOW"

Convert a Unix timestamp to a date

db.events.aggregate([
  { $set: { when: { $toDate: "$ts_ms" } } },                          // milliseconds
  { $set: { when2: { $toDate: { $multiply: ["$ts_s", 1000] } } } }    // seconds
])

Convert a date to a Unix timestamp

db.events.aggregate([
  { $set: { ts_ms: { $toLong: "$createdAt" } } },
  { $set: { ts_s: { $toLong: { $divide: [{ $toLong: "$createdAt" }, 1000] } } } }
])

Timezones

db.events.aggregate([
  { $project: { local: { $dateToString: {
      date: "$createdAt", format: "%Y-%m-%d %H:%M:%S", timezone: "Asia/Kolkata" } } } }
])

Common mistakes

  • $toLong on a fractional result rounds toward zero. Use $floor before it for times before 1970.
  • The BSON Timestamp type is for replication internals. Store application times as Date.
  • Every document's _id already holds its creation second: ObjectId(...).getTimestamp(). See ObjectId timestamp.

Complete example

// mongosh
db.demo.insertOne({ ts_s: 1700000000 })
db.demo.aggregate([
  { $set: { when: { $toDate: { $multiply: ["$ts_s", 1000] } } } },
  { $set: { back: { $toLong: { $divide: [{ $toLong: "$when" }, 1000] } } } }
])

Check any value with the epoch converter, or convert a whole column with the batch converter. All examples use 1700000000 (2023-11-14 22:13:20 UTC) and 1794650400 (2026-11-14 10:00:00 UTC).

Official documentation

Last updated: