JournalSQLFunctions and dates1 min

For Those Who Do Not Know TO_DATE

The to_date function is used to convert data from a text/string type to a date type.

  • TO_DATE
  • string
  • date
  • format mask

What Is the to_date Function?

The to_date function is used to convert data from a text/string type to a date type.

When Should I Use to_date?

For example, you might have a column whose data type is string, even though it actually contains dates. In that case, you will need to use the to_date function.

Syntax of to_date

to_date(column_name, dateformat)

Where instead of column_name, you can write a column name or pass a literal string like '2018-03-02'.

Examples:

If we have a date like '2018-03-02' and want to convert it to a date/datetime, we write:

SELECT TO_DATE('2018-03-02', 'YYYY-MM-DD')

And the output will be:

to_date
------------------------
2018-03-02T00:00:00.000Z

What if we have a date written like 'March 03, 2018' and want to convert it? We write:

SELECT TO_DATE('March 03, 2018', 'Month DD, YYYY')

Output:

to_date
------------------------
2018-03-03T00:00:00.000Z

What if the year is written with only the last two digits?

SELECT TO_DATE('March 03, 18', 'Month DD, YY')

Summary

The takeaway is that you look at how the date is formatted and write a pattern that represents it with the right number of digits, spaces, commas, etc. Of course, you won't memorize every existing pattern, because programmers generally don't memorize everything—you can check the documentation while working: https://www.postgresql.org/docs/7.4/static/functions-formatting.html