Search code examples
c#asp.netdatetimelocalesqldatetime

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


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!


Solution

  • 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.