$dateFromString (Parse String to Date)
Last updated: 2026-10-09
$dateFromString (Parse String to Date)
$dateFromString parses a string into a date using a given format — the inverse of $dateToString, handy for converting imported or front-end date strings into BSON Dates. format uses the same placeholders as $dateToString (%Y, %m, %d...); without it, ISO 8601 is assumed. onError supplies a fallback when parsing fails, onNull when input is null. timezone decides which zone applies when the string carries no zone info.
| Category | Date |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $dateFromString: { dateString: <string>, format: <format>, timezone: <timezone>, onError: <default>, onNull: <default> } }
⚙️ Parameters
| dateString | Required; the date string to parse. |
|---|---|
| format | Optional format pattern; defaults to ISO 8601. |
| timezone | Optional timezone applied when the string lacks zone info. |
| onError / onNull | Optional fallbacks for parse failure and null input. |
Returns:The parsed BSON Date; onError on failure (throws by default), onNull for null input (null by default).
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// $dateFromString: parse imported log timestamps (Beijing time)
db.imports.aggregate([
{ $project: {
createdAt: { $dateFromString: { dateString: '$ts', format: '%Y-%m-%d %H:%M', timezone: 'Asia/Shanghai' } }
} }
])
Output:
{ "_id": 1, "createdAt": ISODate("2026-09-25T08:30:00Z") }
{ "_id": 2, "createdAt": ISODate("2026-09-25T09:00:00Z") }
📌 Notes
- Without format, ISO 8601 is assumed; placeholders like %z parse zone offsets
- Parse failure throws by default — always set onError in production
- Strings without zone info follow timezone, which defaults to UTC
🏷️ Related Tags
💡 Related Cases
📚 Related Tutorials
❓ FAQ
QHow to parse strings with varying formats?
AWithout format, ISO 8601 is tried; when the format is fixed, pass format explicitly.
QDoes parse failure throw?
AYes, unless onError supplies a fallback.
QHow is this different from $toDate?
A$toDate is a loose type conversion; $dateFromString controls format and timezone precisely.