Unable to parse DateTime from a string

前端 未结 6 2068
时光说笑
时光说笑 2020-12-22 10:47
string dt = \"10/25/2010 11:40:05 PM\";
var currentThread = Thread.CurrentThread.CurrentCulture; //ru-RU
DateTime dateTime = DateTime.Parse(dt); //Exception!
         


        
6条回答
  •  清酒与你
    2020-12-22 10:58

    Use a custom Date and Time format string, using either ParseExact or TryParseExact.

    DateTime dateTime;
    DateTime.TryParseExact(
                           dt, 
                           "MM/dd/yyyy hh:mm:ss tt", 
                           CultureInfo.InvariantCulture,
                           DateTimeStyles.None,
                           out dateTime
                          );
    

    The string cannot be parsed as a Russian DateTime representation since the Russian culture doesn't use AM/PM, hence the use of the use of CultureInfo.InvariantCulture which is a US like culture (it represents no specific culture, but is modeled after the en-US one).

提交回复
热议问题