I though about starting a new series that I will add to over time the Friday function, I might not be able to create something as useful as Serge Rielau (@srielau) but maybe it will helpful to someone. Over the last few days I have been asked to some interesting things with “my” data like converting times to a more “friendly” format.
The ask
To convert my nicely cleansed times (19:47:45 or 04:23:32) from various non standard sources (the wonders of Big Data) into a time format that is more compatible with your average email reader (7:47pm or 4:23am) as opposed to a techie that might be all right with the nice 24 hour times. I did a lot of searching around and I could not find any inbuilt functions of DB2 LUW that would do this and so I had to create my own user defined function. Please if you know of anything feel free to correct me, but searching the info center then there was nothing.
DB2 Time to “English” – Code
CREATE FUNCTION GLOBAL.CONVERT_TIME_12H(IN_TIME TIME)
DETERMINISTIC
NO EXTERNAL ACTION
RETURNS VARCHAR(10)
LANGUAGE SQL
BEGIN ATOMIC
----------------------------------------------------------------------------
----------------------------------------------------------------------------
--Takes 24hrs time in gives back 12hrs time suffixed with AM or PM
----------------------------------------------------------------------------
----------------------------------------------------------------------------
DECLARE OUT_TIME VARCHAR(10);
IF(INT(LEFT(IN_TIME,2)) <= 12) THEN
SET OUT_TIME = LEFT(IN_TIME,5) || 'am';
IF(INT(LEFT(IN_TIME,2)) IN (10,11)) THEN
RETURN REPLACE(OUT_TIME,'.',':');
ELSE
RETURN REPLACE(SUBSTR(OUT_TIME,1),'.',':');
END IF;
ELSE
IF(INT(LEFT(IN_TIME,2)) = 24) THEN
SET OUT_TIME = '00:00am';
ELSE
SET OUT_TIME = LEFT((IN_TIME - 12 HOURS),5) || 'pm';
END IF;
RETURN REPLACE(OUT_TIME,'.',':');
END IF;
END
As you can see it takes in standard DB2 time, and I think managed to get all the gotchas like midnight not being 12 hours less. The downside of this function is that the format becomes text and therefore not useable so would not recommend using it for anything but for human format. As I said before if you know of a function to do this in DB2 that is built in I would love to know.
Future articles
In future Friday Functions then I will look at covering non standard asks that I have been required to do. I think after this one I will be needing to create a function to “elongate” a date!
To format timestamps into various print formats, you can use varchar_format. Here’s an example where I reformat the current timestamp into an “English” format:
db2 “values(varchar_format(CHAR(current timestamp),’DAY MONTH DD, YYYY HH12:MM:SS AM’))”
================================
THURSDAY JULY 26, 2012 12:07:12 PM
To take non-standard inputs and turn them into timestamps for DB2, the TIMESTAMP_FORMAT can be used. Arguments are the input string and a mask to describe it to db2.
Thank you for that, how would you get the th, st, nd and rd onto it?