Back to cookbooks list Articles Cookbook

How to Get the Date From a String in Oracle

  • TO_DATE

Problem:

You’d like to convert a string to a date in your result set in Oracle database.

Example:

Our database has a table named accounts_creation, with a field named company_id of the data type NUMBER and two NVARCHAR2 fields named company_name and registration_date as shown below.

company_idcompany_nameregistration_date
1Decathlon5 Jan 1978
2Vestel21 Sep 1991
3White Chapel18 Oct 2017
4Silvercup4 Dec 2021
5JohnnyBros28 Aug 1984

We want to convert the string column registration_date into a date column.

Solution:

We’ll use the TO_DATE() function. Here’s the query:

SELECT 
  company_id,
  company_name,
  TO_DATE(registration_date,'DD Mon YEAR') AS registration_date
FROM accounts_creation;

Here’s the result of the query:

company_idcompany_nameregistration_date
1Decathlon05-JAN-78
2Vestel21-SEP-91
3White Chapel18-OCT-17
4Silvercup4-DEC-21
5JohnnyBros28-AUG-84

Discussion:

The TO_DATE(string, format) function in Oracle converts a string value to a date. The function takes two arguments: the string to convert and the date format. In the format specification, DD signifies the day of the month (1-31), MON signifies the abbreviated name of the month, and YEAR signifies the 4-digit year. You can read more about the available formats in the Oracle SQL documentation here. Here are the most commonly used formats:

FormatMeaning
D Day of week (1-7).
DAY Name of day.
DD Day of month (1-31).
DDD Day of year (1-366).
HH Hour of day (1-12).
HH24 Hour of day (0-23).
MI Minute (0-59).
MM Month (01-12; January = 01).
MON Abbreviated name of month.
MONTH Name of month.
SS Second (0-59).
YEAR Year, spelled out; S prefixes BC dates with a minus sign (-).
YYYY 4-digit year; S prefixes BC dates with a minus sign.

Recommended courses:

Recommended articles:

See also: