how to convert date format c# .net RRS feed

  • Question

  • User1046245955 posted

    anyone got idea on how to convert the date format as (MM/dd/yyyy) in c#

    here's my code:

    DateTime dfrom = Convert.ToDateTime(dtcheck.Rows[i]["datefrom"].ToString());
    DateTime dto = Convert.ToDateTime(dtcheck.Rows[i]["dateto"].ToString());
    DateTime returndate = Convert.ToDateTime(dtcheck.Rows[i]["DATERETURN"].ToString());

    string ldatefrom = string.Format("{0:dd-MMM-yyyy}", dfrom);
    string ldateto = string.Format("{0:dd-MMM-yyyy}", dto);
    string ldatereturn = string.Format("{0:dd-MMM-yy}", returndate);

    note: If i change the format to MM/dd/yyyy still the output is like dd-MMM-yyyy

    Tuesday, May 14, 2019 12:49 PM

All replies

  • User475983607 posted

    Unclear, your code specifically formats the DateTime type as dd-MMM-yyyy.

    Please run your code through the VS debugger and make sure there are not bugs we cannot see.  Otherwise post code so forum members can reproduces this error.  I'm unable to. 

    Perhaps try...

    string ldatefrom = dfrom.ToString("MM/dd/yyyy");

    Also please see the reference docs.


    Tuesday, May 14, 2019 1:37 PM
  • User753101303 posted


    Plus you convert a an object which is likely a DateTime already to a string and then back to DateTime before doing the final conversion.

    Something like that :

                var dtCheck = new DataTable();
                string ldatefrom = String.Format("{0:MM/dd/yyyy}", dtCheck.Rows[0]["datefrom"]);
                Console.WriteLine(ldatefrom); // Shows 05/14/2019

    A common confusion is to not understand that you have how the value is stored (which is the same for everyone) and how it is shown (depending on your country or which tools you are using) as there is no worldwide convention for this.

    My personal preference would be to differ that up to UI rendering. It can also help to make an app that could easily support multiple languages...

    Tuesday, May 14, 2019 3:19 PM