How To Convert Custom Date Format In VB.Net

Problem:

I want to convert my custom 12 hour date and time string into a proper 24 hour DateTime format.

Before:

Custom Date: 13/11/2008 10:08:39 AM

This format is shown as : dd/MM/yyyy hh:mm:ss tt

The only problem with this is that the custom date and time can be up to 4 formats , depending on the time of day , and day of the month.

Example:

13/11/2008 10:08:39 AM = dd/MM/yyyy hh:mm:ss tt

3/11/2008 10:08:39 AM = d/MM/yyyy hh:mm:ss tt

13/11/2008 9:08:39 AM = dd/MM/yyyy h:mm:ss tt

3/11/2008 9:08:39 AM = d/MM/yyyy h:mm:ss tt

Using the DateTime.ParseExact function in VB requires the format to match the custom DateTime format exactly. So as there is only 4 different combinations to this time format , we can use an array and pass it to the function. Example below.

Code:

1
2
3
4
5
6
7
 
Dim CustomDate = "13/11/2008 10:08:39 AM"
 
Dim TimeFormatArray() As String = {"dd/MM/yyyy h:mm:ss tt", "dd/MM/yyyy hh:mm:ss tt", "d/MM/yyyy hh:mm:ss tt", "d/MM/yyyy h:mm:ss tt"}
 
ParseDate = DateTime.ParseExact(CustomDate, TimeFormatArray, Null, Globalization.DateTimeStyles.None)
NewSQLDate = ParseDate.ToString("yyyy-MM-dd HH:mm:ss.fff")

One Response to “How To Convert Custom Date Format In VB.Net”

  1. Jay  on November 19th, 2008

    Hi.
    I can’t find your contacts on website.
    I’m about advertising opportunity at http://gazeek.com.
    Please reply me via email, if you are interested.
    Regards,
    Jay


Leave a Reply