System.FormatException: String was not recognized as a valid DateTime. at System.DateTimeParse.Parse(String s, DateTimeFormatInfo dtfi, DateTimeStyles styles) at System.Convert.ToDateTime(String value)

Kadima 1 Reputation point
2021-05-21T17:13:42.16+00:00

hello,

The application VB get system date convert to string and put it in DateTimeParse.Parse(String s, DateTimeFormatInfo dtfi, DateTimeStyles styles) , System.Convert.ToDateTime(String value) to convert the new string to date that throw exception in some windows 8.1 and 10 machine but
in certain machine this work without prolbème.

the application runs on netframwork 4.8.

Anyone can hlep me

Developer technologies | VB
{count} votes

1 answer

Sort by: Most helpful
  1. Peter Fleischer (former MVP) 19,341 Reputation points
    2021-05-24T13:41:34.51+00:00

    Hi,
    you can reproduce error with following code:

        string s = "";
        var res = System.Convert.ToDateTime(s);
        Console.WriteLine(res);
    

    variable "s" contains string not convertible to date.

    Use TryParse instead:

        string s = "";
        DateTime d;
        if (System.DateTime.TryParse(s, out d))
          Console.WriteLine(d);
        else
          Console.WriteLine("invalid date string");
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.