locked
Error - String was not recognized as a valid DateTime. RRS feed

  • Question

  • User-797751191 posted

    Hi

      I have below code. In Sql Database PostingDate is of Date Datatype. When i change dd/MM/yyyy to dd-MM-yyyy then it works. Secondly i want to check that txtPostingDate is not Null

    Current culture is en-us

    var PostingDate = DateTime.ParseExact(txtPostingDate.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture);

    In txtPostingDate value shown is "29-06-2019"

    <script>
    $(function () {
    $(".datepicker").datepicker(
    {
    dateFormat: 'dd-mm-yy',
    maxDate: new Date
    });
    });
    </script>

    Thanks

    Saturday, June 29, 2019 6:32 PM

Answers

  • 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.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, July 1, 2019 5:43 AM