且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 DB2 中将字符串转换为日期

更新时间:2023-11-11 20:20:04

根据您自己的回答,我猜您的列的数据格式如下:

Based on your own answer, I'm guessing that your column has data formatted like this:

'DD/MM/YYYY HH:MI:SS'

日/月/年之间的实际分隔符无关紧要,年份之后的任何分隔符也无关紧要.

The actual separators between Day/Month/Year don't matter, nor does anything that comes after the year.

您没有说明您使用的是什么版本的 DB2 或它在什么平台上运行,所以我将假设它在 Linux、UNIX 或 Windows 上运行.

You don't say what version of DB2 you are using or what platform it's running on, so I'm going to assume that it's on Linux, UNIX or Windows.

几乎所有最新版本的 DB2 for Linux/UNIX/Windows(8.2 或更高版本,甚至可能是更旧的版本),您都可以使用 TRANSLATE 函数执行此操作:

Almost any recent version of DB2 for Linux/UNIX/Windows (8.2 or later, possibly even older versions), you can do this using the TRANSLATE function:

select 
   date(translate('GHIJ-DE-AB',column_with_date,'ABCDEFGHIJ'))
from
   yourtable

使用此解决方案,列中日期之后的内容无关紧要.

With this solution it doesn't matter what comes after the date in your column.

在 DB2 9.7 中,您还可以使用 TO_DATE 函数(类似于 Oracle 的 TO_DATE):

In DB2 9.7, you can also use the TO_DATE function (similar to Oracle's TO_DATE):

date(to_date(column_with_date,'DD-MM-YYYY HH:MI:SS'))

这要求您的数据与格式字符串匹配;它在查看时更容易理解,但不如 TRANSLATE 选项灵活.

This requires your data match the formatting string; it's easier to understand when looking at it, but not as flexible as the TRANSLATE option.