Search code examples
c#asp.netdatedatetimetextbox

Incorrect date format conversion with TextBox


I want MM/dd/yyyy date format but TextBox gives this date format yyyy-MM-dd. While TextMode is Date.

<asp:TextBox ID="txtChkEventDate" TextMode="Date" runat="server"></asp:TextBox>

I've used this code to convert the format:

string[] formats = { "MM/dd/yyyy" };
var dateTime = DateTime.ParseExact(txtChkEventDate.Text, formats, 
                    new CultureInfo("en-US"), DateTimeStyles.None);

But it show error:

String was not recognized as a valid DateTime.

How I can convert yyyy-MM-dd into MM/dd/yyyy date format?


Solution

  • Based on your comment on the question:

    value is 2017-12-14

    That input doesn't match the format string you're using: "MM/dd/yyyy"

    You have to use a format string which matches your source format: "yyyy-MM-dd"

    For example:

    var dateTime = DateTime.ParseExact(txtChkEventDate.Text, "yyyy-MM-dd", new CultureInfo("en-US"), DateTimeStyles.None);
    

    When parsing a value from a string, the format string you use is what matches the incoming data string. If you want to output the parsed value in a different format at a later time, that's when you'd use a different format string to specify that output. For example:

    someLabel.Text = dateTime.ToString("MM/dd/yyyy");