Convert DateTime to ODBC time format


Recent question on this side of the firewall…

 

Want a datetime in this format?

2004-06-21T11:29:01.9346744-08:00

 

In .NET Framework 2.0: DateTime.ToString(“o”) ;

In .NET Framework 1.0\1.1: DateTime.ToString(“yyyy-MM-ddTHH:mm:ss.fffffffzzz”);

 

Comments (26)

  1. RichB says:

    Your .Net 1.0/1.1 solution is incorrect. The output will change depending on culture. Provide the invariant culture to the ToString() so that non-gregorian cultures aren’t accidently used, and it would also be a good idea to escape the : tokens inside the string.

  2. Yes, please, a SIMPLE WAY to obtain the datetime in ODBC format!!!

  3. Andrea says:

    /* DateTime: */

    DateTime dt = DateTime.Now;

    /* Conversion: */

    Console.WriteLine("1: " + dt.ToString("yyyy-MM-ddTHH\:mm\:ss.fffffffzzz"));

    /* With culture */

    string formatString= "yyyy-MM-ddTHH:mm:ss.fffffffzzz";

    System.Globalization.CultureInfo CInfo= new System.Globalization.CultureInfo("en-US", true);

    Console.WriteLine("2: " + dt.ToString(formatString,CInfo));

  4. Keith Patrick says:

    Is the "o" defined somewhere as a constant with any other common constants the method would use, or is the magic string gonna be it?

  5. Somewhat-related side note: oddly, DTS doesn’t allow you to import datetimes in this format–you have to remove the "T" in the middle. Unless, of course, I’ve missed something obvious (in which case, plese enlighten me :) ).