The largest data and database services provider in North America | Speak with Us
On Date Formats in DB2 – Part 2
Here is a follow-up question and answer based on my previous blog post:
Q: My format does not fit into any of the formats listed in the DB2 manuals. What if I have a DATE stored like YYYYMMDD (with no dashes or slashes) and I want to compare it to a DB2 date?
A: Okay, let’s look at one potential solution to your problem (and then I want to briefly talk about the use of proper data types). First of all you indicate that your date column contains dates in the following format: yyyymmdd with no dashes or slashes. You do not indicate whether this field is a numeric or character field – I will assume that it is character. If it is not, you can use the CHAR function to convert it to a character string.
Then, you can use the SUBSTR function to break the character column apart into the separate components, for example SUBSTR(column,1,4) returns the year component, SUBSTR(column,5,2) returns the month, and SUBSTR(column,7,2) returns the day.
Then you can concatenate all of these together into a format that DB2 recognizes, for example, the USA format which is mm/DD/yyyy. This can be done as follows:
SUBSTR(column,5,2) || “/” || SUBSTR(column,7,2) ||
“/” || SUBSTR(column,1,4)
Then you can use the DATE function to convert this character string into a DATE that DB2 will recognize. This is done as follows:
DATE(SUBSTR(column,5,2) || “/” || SUBSTR(column,7,2) ||
“/” || SUBSTR(column,1,4))
The result of this can be used in date arithmetic with other dates or date durations. Of course, it may not perform extremely well, but it should return the results you desire.
Now, a quick word about using proper data types… I say this all of the time, but there are many applications and implementations “out there” that do not heed the advice: it is wise to use the DATE data type when you store dates in DB2 tables. It simplifies life later on when you want to do things like formatting dates and performing date arithmetic.
Using the appropriate data type also ensures that DB2 will perform the proper integrity checks on the columns when data is entered, thereby ensuring that only valid dates actually get stored in date columns. When using another data type (numeric or character), you will have to code logic into your application programs (and/or create validation triggers) to ensure that only valid dates are entered into the database.
This blog was originally published on Craig Mullins blog at: http://db2portal.blogspot.com/2008/11/on-date-formats-part-2.html