Muistiinpano
Tämän sivun käyttö edellyttää valtuutusta. Voit yrittää kirjautua sisään tai vaihtaa hakemistoa.
Tämän sivun käyttö edellyttää valtuutusta. Voit yrittää vaihtaa hakemistoa.
Applies to:
Databricks SQL
Databricks Runtime
Returns expr cast to a date using an optional formatting.
Syntax
to_date(expr [, fmt] )
Arguments
expr: A STRING expression representing a date.- fmt: An optional format STRING expression.
Returns
A DATE.
If fmt is supplied, it must conform with Datetime patterns.
If fmt is not supplied, the function is a synonym for cast(expr AS DATE).
If fmt is malformed or its application does not result in a well formed date, Azure Databricks raises an error.
To return NULL instead of an error when expr is malformed, use try_cast(expr AS DATE) or, in Databricks Runtime, set spark.sql.ansi.enabled to false.
Common error causes and resolutions
to_date raises an error when:
- The input string doesn't match the expected format: When
fmtis not specified, the input must be inyyyy-MM-ddoryyyy-MM-dd HH:mm:ssformat. If your data uses a different format, such asdd/MM/yyyyorMM-dd-yyyy, specify the matchingfmtargument. See Datetime patterns for all supported pattern letters. - The input string contains invalid date values: For example, month
13, day32, or non-numeric characters where digits are expected. - The format string uses unsupported pattern letters: See Datetime patterns for supported symbols and formatting rules.
Error conditions
- CAST_INVALID_INPUT: Raised when no
fmtis provided and the input string cannot be parsed as a date. - CANNOT_PARSE_TIMESTAMP: Raised when
fmtis provided but the input string does not match the given format pattern.
Note
In Databricks Runtime, if spark.sql.ansi.enabled is false, the function returns NULL instead of an error for malformed dates.
Examples
-- Parsing with default format (yyyy-MM-dd)
> SELECT to_date('2009-07-30 04:17:52');
2009-07-30
-- Parsing with an explicit format
> SELECT to_date('2016-12-31', 'yyyy-MM-dd');
2016-12-31
-- Parsing a non-default date format
> SELECT to_date('31/12/2016', 'dd/MM/yyyy');
2016-12-31
-- Error: input is not a valid date string
> SELECT to_date('not-a-date');
Error: CAST_INVALID_INPUT
-- Error: input format doesn't match the default yyyy-MM-dd format
> SELECT to_date('31/12/2016');
Error: CAST_INVALID_INPUT
-- Fix: supply a fmt that matches the input format
> SELECT to_date('31/12/2016', 'dd/MM/yyyy');
2016-12-31
-- Use try_cast to return NULL instead of an error for invalid input
> SELECT try_cast('not-a-date' AS DATE);
NULL