Bob,
I see you got pretty close using TO-CHAR function, alternate name for TIMESTAMP_FORMAT.
I have not really used that much before if at all.
I use SQL like a programming language.
You could have done a simple REPLACE to insert the other bits in place of the intervening blank:
REPLACE(to_char(DT,'DD Month'), ' '
,strip(char(day(dt))) concat
substr('th st nd rd '
,int(substr('1230000000000000000012300000001',day(dt), 1))
*3+1, 3) concat 'of ')
I did not test this. Just off top of my head.
Could be like a fun challenge, to see who can do it in less characters of code.
There might be an even more concise solution still with good performance.
------------------------------
Michael Hannan
DB2 SQL and Performance Specialist
------------------------------
Original Message:
Sent: Jan 13, 2021 02:18 PM
From: Bob Kota
Subject: TO_CHAR Examples
Hello. I hope you are well.
I have a need to convert a date into string. I've been able to use the to_char function on some pieces, but am having difficulties with the following two items. I'm not sure if the capability exists.
- Output the day of month with the ordinal suffix (st/nd/rd/th). For example, 2021-02-01 output as 1st and 2021-01-28 is returned as 28th.
SELECT to_char(DT_GREGORIAN, 'FMDDth')
FROM Table
WHERE DT_GREGORIAN = '2021-01-13'
AND CD_CO = 33
WITH UR;
DSNT408I SQLCODE = -20447, ERROR: FORMAT STRING FMDDth IS NOT VALID FOR THE
TO_CHAR FUNCTION
- Output the date as DD of Month, like "1st of January" and "28th of September". In this case, I am able to output day and month in the desired format, but not with the word 'or' in the middle'.
SELECT to_char(DT_GREGORIAN, 'DD "of" Month')
FROM Table
WHERE DT_GREGORIAN = '2021-01-13'
AND CD_CO = 33
WITH UR;
DSNT408I SQLCODE = -20447, ERROR: FORMAT STRING DD "of" Month IS NOT VALID
FOR THE TO_CHAR FUNCTION
This SQL works
SELECT to_char(DT_GREGORIAN,'DD Month')
FROM Table
WHERE DT_GREGORIAN = '2021-01-13'
AND CD_CO = 33
WITH UR;
---------+---------+---------+---------+------
13 January
------------------------------
Bob Kota
------------------------------