Convert Date from 6/05/2020 format to dd/MM/YYYY format

后端 未结 5 1171
面向向阳花
面向向阳花 2020-12-03 18:24

I am facing a small issue which i am not able after trying so many things so here it goes ..... There is a text box in my page in which i am entering date and i want that da

5条回答
  •  长情又很酷
    2020-12-03 19:23

    EDIT: This value: "11/2/2010" doesn't match the format "dd/MM/yyyy". It matches the format "d/M/yyyy" - for "dd/MM/yyyy" it should be "11/02/2010".

    That's why TryParseExact is failing for you. You need to pick the right format pattern.


    A DateTime value doesn't have a format. It just represents date and time (in the ISO calendar, and possibly in different time zones, but that's a different matter). It's like an int - it doesn't represent "a decimal integer" or "a hex integer" - it's just an integer within a particular range. You can format a number as decimal or hex, but it doesn't inherently have a format.

    It sounds like you should parse it with ParseExact to specify the format when converting from the textbox, or probably TryParseExact:

    // This is assuming you're absolutely sure of the format used. This is *not*
    // necessarily the user's preferred format. You should think about where your
    // data is coming from.
    DateTime date;
    if (DateTime.TryParseExact(text, "dd/MM/yyyy", CultureInfo.InvariantCulture,
                               DateTimeStyles.None, out date))
    {
        // Okay, successful parse. We now have the date. Use it, avoiding formatting
        // it back to a string for as long as possible.
    }
    

    You should keep that value as DateTime for all purposes except giving it back to a user - at which point you may well want to use their cultural settings.

    In particular, if you're storing the value in a database you should not convert it to text and include it in a SQL statement - that's asking for trouble. Instead, use a parameterized SQL statement and set it as the parameter value, still as a DateTime.

提交回复
热议问题