Using DateTime.ParseExact to load a DB2 timestamp to .NET

It would be nice if the only database you ever needed to access from .NET was SQL Server, or something similar to it, that .NET understood and worked with easily. One of my clients makes extensive use of DB2, though, and not a recent version--a version old enough that there is no LINQ provider. So, part of my job is working around some of the oddities of pulling out of DB2 and sometimes writing the result into .NET.

Recently I had to pull a DB2 timestamp and save out something like a timestamp in SQL Server. As you probably know, the SQL Server timestamp is not a timestamp as all, at least not like DB2's. So when I needed to pull the timestamp from DB2 and get some semblance of a timestamp in SQL Server, I needed to convert to a DateTime in .NET.

Luckily, DateTime.ParseExact was there to save the day. DateTime.ParseExact provides methods to allow you to describe in detail the format of the value you will be passing in, and have the resulting DateTime parse out the string exactly as you describe it.

The solution is pretty simple (assuming dateField is the input string with the DB2 timestamp):


Dim cultureInfo As New CultureInfo("en-US")
Dim dateTime As DateTime = DateTime.ParseExact(dateField, "yyyy-MM-dd-HH.mm.ss.ffffff", cultureInfo)


Note the ".ffffff" at the end of the format string. This allows you to specify fractions of a second, which will be coming in on the input string. Unfortunately, this information will be stripped off, and you will lose the fraction part. But at least you now have a DateTime you can save successfully into SQL Server!

Good luck out there!

1 comments:

Anonymous said...

Not HH.mm.ss.ffffff!
But HH:mm:ss.ffffff!

Post a Comment