Validate Date RRS feed

  • Question

  • User-797751191 posted


      What is the difference between below 2 statement . Are both ok

    PDate = DateTime.ParseExact(txtPDate.Text, "dd-MM-yyyy", CultureInfo.InvariantCulture);
    PDate = DateTime.Parse(txtPDate.Text);


    Friday, July 5, 2019 6:05 AM


  • User839733648 posted

    Hi jsshivalik,

    It is the difference usage of DateTime. Parse() method and DateTime.ParseExact() method.

    DateTime.Parse() is more simple method to convert string date time representation to DateTime object.

    DateTime.ParseExact() is more strict and it trys to comply with the specified date format and culture. 

    For example:

                string myDate = "07/05/2019";
                DateTime myDateParse = DateTime.Parse(myDate);
                DateTime myDateParseExact = DateTime.ParseExact(myDate, "dd/MM/yyyy", CultureInfo.InvariantCulture);

    Both DateTime.Parse() and DateTime.ParseExact() will successfully convert string to DateTime object.

    However, if we change the string date to a different format like:

    string myDate = "2019/07/05";

    DateTime.Parse() will succeed but DateTime.ParseExact() will fail because the date format does not match "dd/MM/yyyy".

    There will be an error: String was not recognized as a valid DateTime.

    For more about DateTime.Parse(), you could refer to: https://docs.microsoft.com/en-us/dotnet/api/system.datetime.parse?view=netframework-4.8

    For more about DateTime.ParseExact(), you could refer to: https://docs.microsoft.com/en-us/dotnet/api/system.datetime.parseexact?view=netframework-4.8

    Best Regards,


    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, July 5, 2019 7:06 AM