Unable to parse DateTime from a string

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

提交回复
热议问题