$dateDiff (Date Difference)

Last updated: 2026-10-09

$dateDiff (Date Difference)

$dateDiff computes the difference between two dates in a given unit as an integer — ideal for ages, subscription lengths, or dwell times. unit supports year, month, week, day, hour, minute, second, and millisecond; results truncate to whole-unit boundaries (year counts only complete years). startOfWeek sets the week start and applies only when unit is week. timezone drives the calendar used; always set it across zones.

CategoryDate
MongoDB Version5.0+
Example Languagemongosh (Shell)

📝 Syntax

{ $dateDiff: { startDate: <date-expression>, endDate: <date-expression>, unit: <unit>, timezone: <timezone>, startOfWeek: <week-start> } }

⚙️ Parameters

startDate / endDateRequired; the start and end dates.
unitRequired; the difference unit (the 8 units above).
timezoneOptional timezone for the calculation.
startOfWeekOptional; applies only when unit is week; values like Monday, Sunday.

Returns:The integer difference (endDate minus startDate); null if either date is null.

▶ Example

Run the commands below in your local mongosh (requires a running mongod):

// $dateDiff: compute age in years
 db.users.aggregate([
  { $project: {
      ageYears: { $dateDiff: { startDate: '$birthDate', endDate: '$$NOW', unit: 'year' } }
  } }
])

Output:

{ "_id": 1, "ageYears": 28 }
{ "_id": 2, "ageYears": 31 }

📌 Notes

More hands-on cases coming soon.

📚 Related Tutorials

❓ FAQ

QDoes the result have decimals?
ANo — $dateDiff returns integers, truncated at unit boundaries.
QCan the difference be negative?
AYes — negative when endDate is earlier than startDate.
QHow to count days between two dates?
ASet unit to day; note timezone shifts calendar-day boundaries.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏