Two-Way Date-String Conversion (in .Net)

If you need to store and retrieve dates as string (in a CSV file, for example), here's one way to handle it (in VB.net).

(And if you know a better way -- please show me)




    Const FORMAT As String = _
         "yyyyMMddHHmmss" 'Example format
    Dim s1 As String = "20040610140023"
    Dim s2 As String

    Dim d As Date

    'Turn s1 into a date
    d = Date.ParseExact _
         (s1, FORMAT, _
         System.Globalization.DateTimeFormatInfo.InvariantInfo)

    'Turn the date back into a string
    s2 = String.Format("{0:" & FORMAT & "}", d)

    'Compare the starting and final strings
    Debug.Assert(s1.Equals(s2), _
         "The strings s1 and s2 should be equal")


 

My book "Choose Your First Product" is available now.

It gives you 4 easy steps to find and validate a humble product idea.

Learn more.

(By the way, I read every comment and often respond.)

Your comment, please?

Your Name
Your Url (optional)
Note: I may edit, reuse or delete your comment. Don't be mean.