User665608656 posted
Hi jsshivalik,
According to your description, the reason for this error message
Error - String was not recognized as a valid DateTime.
is that txtPostingDate.Text does not match the format of "dd/MM/yyyy".
As you said, when you modify it to dd-MM-yyyy, it works. You could refer to this link :
https://docs.microsoft.com/en-us/dotnet/api/system.datetime.parseexact?view=netframework-4.8#System_DateTime_ParseExact_System_String_System_String_System_IFormatProvider_
If you want to store it as 'dd/MM/yyy', you need to change the format of txtPostingDate.Text to 'dd/MM/yyyy' as well.
First, you can directly change dateFormat:'dd-mm-yy' to dateFormat:'dd/MM/yyy'.
In the second way, you can format txtPostingDate.Text into the 'dd/MM/yyyy' type like this:
var PostingDate = DateTime.ParseExact(Convert.ToDateTime(txtPostingDate.Text.ToString()).ToString("dd/MM/yyyy"), "dd/MM/yyyy", CultureInfo.InvariantCulture);
For your second question ,if you want to check the txtPostingDate is not null,you can refer to the following code:
if (txtPostingDate != null && !string.IsNullOrEmpty(txtPostingDate.Text.ToString()))
{
var PostingDate = DateTime.ParseExact(Convert.ToDateTime(txtPostingDate.Text.ToString()).ToString("dd/MM/yyyy"), "dd/MM/yyyy", CultureInfo.InvariantCulture);
}
Best Regards,
YongQing.