Last post Jul 05, 2019 07:06 AM by Jenifer Jiang
Jul 05, 2019 06:05 AM|jsshivalik|LINK
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);
Jul 05, 2019 07:06 AM|Jenifer Jiang|LINK
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.
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