Unable to parse DateTime from a string

前端 未结 6 2034
时光说笑
时光说笑 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).

    0 讨论(0)
  • 2020-12-22 11:05

    Try something like this:

    dateTime = DateTime.Parse(dt, CultureInfo.CreateSpecificCulture("en-US"));
    
    0 讨论(0)
  • 2020-12-22 11:18

    Try using ParseExact instead:

    DateTime myDate = DateTime.ParseExact("10/25/2010 11:40:05 PM", "MM/dd/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);
    
    0 讨论(0)
  • 2020-12-22 11:18

    Russia doesn't use AM and PM as their AM/PM designators, which is at least one reason that would fail. Another is that Russia may not use the "month/day/year" format which is mostly a peculiarity of the US as far as I'm aware. (I can't remember Russia's format strings offhand; I do remember that the genitive month names caused me grief recently, but that's another story...)

    I would personally explicitly specify the culture as the invariant culture, and also explicitly specify the format string:

    string text = "10/25/2010 11:40:05 PM";
    string pattern = "MM/dd/yyyy hh:mm:ss tt";
    DateTime dt = DateTime.ParseExact(text, pattern,
                                      CultureInfo.InvariantCulture);
    

    If this might reasonably be expected to fail, you should use DateTime.TryParseExact instead, to handle failure gracefully without involving exceptions.

    0 讨论(0)
  • 2020-12-22 11:22
    var result = DateTime.ParseExact(dt, 
                                     "MM/dd/yyyy hh:mm:ss tt", 
                                     CultureInfo.InvariantCulture);
    

    To avoid runtime exceptions use safe DateTime.TryParseExact() method, it returns false in case of unsuccessfull parsing rather than throwing the FormatException exception

    0 讨论(0)
  • 2020-12-22 11:23

    Try DateTime.Parse(dt, CultureInfo.GetCultureInfo("EN-us"))

    0 讨论(0)
自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题