Oracle's TO_DATE function converts a string to a DATE value using a specified format model; for example, TO_DATE('2024-06-15', 'YYYY-MM-DD') yields June 15, 2024.
Background: Oracle DATE Storage and Semantics
Oracle's DATE data type stores year, month, day, hour, minute, and second—never fractional seconds or time zone information. It does not distinguish between local time and UTC; applications must handle time zone logic separately. Internally, Oracle uses seven bytes to store century, year, month, day, hour (0–23), minute, and second (each with base-1 offset for hour/minute/second). Because DATE includes time components, two entries with identical year-month-day but different hours are different values. This differs from some databases that offer separate DATE (calendar date only) and TIMESTAMP types.
How TO_DATE Works: Syntax and Components
The full syntax is: TO_DATE(char [, format_mask [, nls_param]]).
char: Input string—must match the provided format model or default session settings, or Oracle raisesORA-01861: literal does not match format string.format_mask: Required if the string doesn’t match the default date format (usuallyDD-MON-YYin many installations, but this is session- and database-configurable viaNLS_DATE_FORMAT).nls_param: Optional, e.g.,'NLS_DATE_LANGUAGE = AMERICAN', to control language-specific elements like month names.
The function returns a DATE value with time components set to midnight (00:00:00) if omitted in the input string. To include time, the format mask must specify hour, minute, and second elements explicitly.
Common Format Elements and Examples
Format models use specific element codes. Here are frequently used ones:
YYYYorYEAR: Four-digit or spelled-out year (e.g., 2024 or TWO THOUSAND TWENTY-FOUR)MM: Two-digit month (01–12)MON: Three-letter abbreviation (JAN, FEB, …)MONTH: Full month name (JANUARY, …)DD: Day of month (01–31)HH24: Hour (00–23);HH12orHH: 12-hour clock (01–12)MI: Minutes (00–59)SS: Seconds (00–59)AMorPM: Meridiem indicator (required with 12-hour formats)
Examples:
TO_DATE('15-JUN-2024', 'DD-MON-YYYY')TO_DATE('20240615', 'YYYYMMDD')TO_DATE('15/06/2024 14:30:45', 'DD/MM/YYYY HH24:MI:SS')TO_DATE('June 15, 2024 2:30 PM', 'MONTH DD, YYYY HH:MI AM', 'NLS_DATE_LANGUAGE = AMERICAN')
Notice that month names in formats like MONTH or MON must match the language specified by NLS_DATE_LANGUAGE; mismatched languages cause conversion errors even if the numeric parts are correct.
Choosing the Right Format Mask
Selecting a format mask requires matching the input string exactly—not just in structure but in spacing, punctuation, and case. A common mistake is assuming MON is case-insensitive; while Oracle ignores case in TO_DATE parsing, inconsistent casing in the input string can lead to errors if the session’s NLS_DATE_LANGUAGE expects uppercase abbreviations (e.g., 'jun' may fail if the session expects 'JUN' in some locales).
Best practices include:
- Always specify the format mask explicitly rather than relying on
NLS_DATE_FORMAT, which varies across sessions and environments (development vs. production). - Use four-digit years (
YYYY) to avoid century ambiguity (e.g.,'24'could become 2024 or 1924 depending on the defaultRRorYYbehavior). - Include time elements only if needed; omitting them sets time to midnight, which may affect range queries (e.g.,
WHERE order_date = TO_DATE('2024-06-15', 'YYYY-MM-DD')excludes records with time > 00:00:00).
Common Pitfalls and Fixes
Several errors arise repeatedly when using TO_DATE:
- Whitespace mismatches: Extra or missing spaces between elements (e.g.,
'2024 06 15'vs.'YYYY MM DD') cause mismatches. Trim whitespace withTRIM()or useFMprefix in the format mask to suppress padding (e.g.,'FMDD/MM/YYYY'). - Invalid dates:
TO_DATE('30-FEB-2024', 'DD-MON-YYYY')fails because February 30 does not exist. Oracle validates calendar correctness. - Two-digit year ambiguity: Using
YYorRRcan misinterpret decades. ForRR, years 00–49 map to 2000–2049; years 50–99 map to 1950–1999. This can cause silent logic errors in legacy data imports. - Time zone confusion:
TO_DATEproduces a database-local time; if data originates from multiple time zones, the value may be incorrect unless adjusted (e.g., viaFROM_TZandAT TIME ZONEforTIMESTAMP WITH TIME ZONE).
Debug tip: Use SELECT TO_CHAR(your_date_column, 'YYYY-MM-DD HH24:MI:SS') FROM ... to inspect stored values and compare against expectations.
Comparison with Related Functions
Oracle provides several date-conversion functions, each with distinct roles:
TO_TIMESTAMP: Converts a string to aTIMESTAMP(supports fractional seconds viaFFformat element). Use when precision beyond seconds matters.TO_TIMESTAMP_TZ: Adds time zone offset or region name (e.g.,TO_TIMESTAMP_TZ('2024-06-15 14:30:00 -05:00', 'YYYY-MM-DD HH24:MI:SS TZH:TZM')).TO_YMINTERVALandTO_DSINTERVAL: Convert strings to interval types (e.g.,TO_DSINTERVAL('10 05:30:00')for 10 days, 5 hours, 30 minutes).TO_NUMBERorTO_CHARconversions involving dates often useTO_CHAR(date, 'format')to extract parts (e.g.,TO_CHAR(hire_date, 'YYYY') AS hire_year).
Key distinction: DATE is fixed-precision (seconds), whereas TIMESTAMP supports up to 9 digits of fractional seconds. If your application requires microsecond-level timing (e.g., high-frequency trading logs), avoid TO_DATE and use TO_TIMESTAMP instead.
Performance and Safety Considerations
Using TO_DATE in a WHERE clause can hinder index usage if the column is indexed and the expression wraps the column (e.g., TO_DATE(date_col) = ... prevents index scans). Instead, ensure the column remains unmodified and convert the literal: date_col = TO_DATE('2024-06-15', 'YYYY-MM-DD') allows index use.
Another safety point: Avoid implicit conversions. If you write WHERE date_col = '2024-06-15' and date_col is a DATE, Oracle attempts to convert the string using NLS_DATE_FORMAT. If the session’s format differs, the comparison fails or returns incorrect results. Always use TO_DATE explicitly for clarity and reliability.
Finally, be cautious with NLS_DATE_LANGUAGE defaults in multi-language deployments. An application expecting English month names may break if deployed in a French session unless NLS_DATE_LANGUAGE = FRENCH is set. Use NLS_LANG or embedded NLS_PARAM arguments to enforce consistency.
Handling Edge Cases: Leap Years, End-of-Month, and DST
Oracle’s DATE type correctly handles leap years (e.g., TO_DATE('29-FEB-2024', 'DD-MON-YYYY') succeeds for 2024, a leap year, but fails for 2023). However, it does not account for daylight saving time (DST) transitions because it stores no time zone context. If your application must adjust for DST (e.g., scheduling recurring events), use TIMESTAMP WITH TIME ZONE and functions like NEW_TIME or FROM_TZ to apply region-specific rules.
For end-of-month calculations, LAST_DAY(TO_DATE('01-MAR-2024', 'DD-MON-YYYY')) returns 31-MAR-2024 correctly, even across leap-year boundaries. But note that adding months with ADD_MONTHS adjusts the day to the last valid day of the target month (e.g., ADD_MONTHS(TO_DATE('31-JAN-2024', 'DD-MON-YYYY'), 1) yields 29-FEB-2024).
Frequently Asked Questions
Can I use TO_DATE with only a year and month?
Yes. If your input is '2024-06', use TO_DATE('2024-06', 'YYYY-MM'), which returns the first day of that month at midnight (e.g., June 1, 2024 00:00:00). This is useful for monthly aggregations where the day component is irrelevant.
Why does TO_DATE sometimes accept two-digit years without error?
When using the RR format element (e.g., TO_DATE('24-06-15', 'RR-MM-DD')), Oracle applies a sliding window: years 00–49 map to 2000–2049, and 50–99 map to 1950–1999. So '24' becomes 2024, but '50' becomes 1950. This was designed for Y2K compatibility but is now discouraged in favor of explicit YYYY.
Is TO_DATE case-sensitive for month names?
Oracle’s TO_DATE treats month abbreviations like JAN or jan as equivalent during parsing, but the session’s NLS_DATE_LANGUAGE must match the name’s language. For instance, 'JUN' works in English sessions, but 'JUN' fails in a French session unless NLS_DATE_LANGUAGE = FRENCH is set (where June is JUIN).
How do I convert a Unix timestamp (seconds since 1970-01-01) to Oracle DATE?
Oracle does not have a built-in Unix timestamp function, but you can compute it: TO_DATE('1970-01-01', 'YYYY-MM-DD') + (unix_timestamp / 86400). Since Oracle DATE arithmetic uses days, dividing seconds by 86400 converts to fractional days. For example, 1,718,400,000 seconds yields TO_DATE('1970-01-01', 'YYYY-MM-DD') + 19888.888..., which equals June 15, 2024 21:20:00.
Does TO_DATE support fractional seconds?
No. The DATE type has no fractional second precision, so TO_DATE('2024-06-15 14:30:45.123', 'YYYY-MM-DD HH24:MI:SS.FF') will raise ORA-01821: date format not recognized. Use TO_TIMESTAMP instead, which accepts the FF format element for up to 9 digits of sub-second precision.
What happens if I pass NULL to TO_DATE?
Oracle returns NULL if any argument is NULL. For example, TO_DATE(NULL, 'YYYY-MM-DD') evaluates to NULL, not an error. This is useful in conditional expressions like NVL(input_str, '1900-01-01') to avoid conversion errors from missing data.