$dateFromParts (Construct Date from Parts)

Last updated: 2026-10-09

$dateFromParts (Construct Date from Parts)

$dateFromParts builds a date from numeric parts such as year, month, day, hour, minute, second, and millisecond — the inverse of $dateToParts. It has two modes: calendar fields (year, month, day...) or ISO 8601 week fields (isoWeekYear, isoWeek, isoDayOfWeek). Unspecified fields take their minimum (month defaults to 1, hour to 0). Useful for rebuilding dates from stored components or building range boundaries. timezone sets the resulting date's zone and defaults to UTC.

CategoryDate
MongoDB Version1.0+
Example Languagemongosh (Shell)

📝 Syntax

{ $dateFromParts: { year: <number>, month: <number>, day: <number>, hour: <number>, minute: <number>, second: <number>, millisecond: <number>, timezone: <timezone> } }

⚙️ Parameters

yearRequired; year in calendar mode, or isoWeekYear in ISO mode.
month / isoWeekMonth (default 1) or ISO week; use only the fields of one mode.
day / isoDayOfWeekDay (default 1) or ISO day of week.
hour/minute/second/millisecondOptional; default to 0.
timezoneOptional timezone for the constructed date.

Returns:The constructed BSON Date; null if year is missing.

▶ Example

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

// $dateFromParts: rebuild event time from parts (Beijing time)
db.events.aggregate([
  { $project: {
      startedAt: { $dateFromParts: { year: '$y', month: '$m', day: '$d', timezone: 'Asia/Shanghai' } }
  } }
])

Output:

{ "_id": 1, "startedAt": ISODate("2026-09-25T00:00:00Z") }
{ "_id": 2, "startedAt": ISODate("2026-10-01T00:00:00Z") }

📌 Notes

More hands-on cases coming soon.

📚 Related Tutorials

❓ FAQ

QCan I build a date from year only?
AYes — month defaults to 1, day to 1, and time parts to 0.
QCan I mix calendar and ISO fields?
ANo — calendar and ISO fields are mutually exclusive; mixing throws.
QDo out-of-range values throw?
AYes, e.g. month 13 or day 32 throws — validate before passing.
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%

🙏 帮我们做得更好

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

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