Check if a string contains date or not

后端 未结 4 1951
無奈伤痛
無奈伤痛 2021-01-02 03:19

Given a string \"15:30:20\" and \"2011-09-02 15:30:20\", How can I dynamically check if a given string contains date or not?

\"15:3         


        
4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-02 03:28

    Use DateTime.TryParseExact Method.

    string []format = new string []{"yyyy-MM-dd HH:mm:ss"};
    string value = "2011-09-02 15:30:20";
    DateTime datetime;
    
    if (DateTime.TryParseExact(value, format, System.Globalization.CultureInfo.InvariantCulture,System.Globalization.DateTimeStyles.NoCurrentDateDefault  , out datetime))
       Console.WriteLine("Valid  : " + datetime);
    else
      Console.WriteLine("Invalid");
    

提交回复
热议问题