C# string to SqlDateTime: how to set format for recognition?

Askar Ibragimov picture Askar Ibragimov · May 29, 2013 · Viewed 7.7k times · Source

I need to use

SqlDateTime.Parse(val)

where val is a string such as " 23.3.1992 00:00:00 ".

The string is in European format, that is, day precedes month. However Parse wants "American" format. How I can tell it to use particular datetime format / locale?

Thanks in advance!

Answer

Khadim Ali picture Khadim Ali · May 29, 2013

Try this:

string val = "23.12.1992 00:00:00";

// Parse exactly from your input string to the native date format.
DateTime dt = DateTime.ParseExact(val, "dd.M.yyyy hh:mm:ss", null);

// Part to SqlDateTime then            
System.Data.SqlTypes.SqlDateTime dtSql = System.Data.SqlTypes.SqlDateTime.Parse(dt.ToString("yyyy/MM/dd"));

This could be done in one statement, but just separated for illustration.