Home > Software design >  "String was not recognized as a valid DateTime." format "yyyy-MM-dd" how i can u
"String was not recognized as a valid DateTime." format "yyyy-MM-dd" how i can u

Time:11-05

My script from txtdate;

<asp:TextBox ID="txtDate1" AutoComplete="off"  runat="server" ></asp:TextBox>

<script type="text/javascript">
$(function () {
    $('[id*=txtDate]').datepicker({
        changeMonth: true,
        changeYear: true,
        format: "yyyy/MM/dd",
        language: "tr"
    });
});
</script>

I try to use format in my date time

DateTime x = DateTime.ParseExact(txtDate1.Text, "yyyy-MM-dd", new CultureInfo("en-US")).AddDays(7);

I get an error:

String was not recognized as a valid DateTime

But this format works:

DateTime x = DateTime.ParseExact(txtDate1.Text, "dd/MM/yyyy", new CultureInfo("en-US")).AddDays(7);

How can I use format "yyyy-MM-dd" ?

CodePudding user response:

In your JS it looks like you expecting string that contains date in this format format: "yyyy/MM/dd So both of your parsing should be invalid.

So how this DateTime.ParseExact works:

You have input string that can be formatted in different ways.

DateTime.ParseExact is defined:

public static DateTime ParseExact (string s, string format, IFormatProvider? provider);

docs: https://docs.microsoft.com/en-us/dotnet/api/system.datetime.parseexact?view=net-5.0

  • So what it means is that s is input date string that you want to parse.
  • String format tells the method what format is your input string.
  • And provider is an object that supplies culture-specific format information about s.

So example:

var dateString = "11/04/2021";

If you do:

 var date = DateTime.ParseExact(dateString, "dd/MM/yyyy", new CultureInfo("en-US"));

Your date will be 11th April 2021

But if you do:

var date = DateTime.ParseExact(dateString, "MM/dd/yyyy", new CultureInfo("en-US"));

Your date will be 4th November 2021

Addition:

If you try this:

var date = DateTime.ParseExact(dateString, "MM-dd-yyyy", new CultureInfo("en-US"));

You will be thrown System.FormatException: "String was not recognized as a valid DateTime." simply because string is "11/04/2021" and you telling your parser to expect "MM-dd-yyyy" Hope its clearer now.

  • Related