Retain MM/dd/yyyy format when converting string to DateTime RRS feed

  • Question

  • User-73514677 posted


    I have a string containing value in the format of 11/22/2019 00:00:00

    I want to store this in a DateTime column.

    I have tried this:

    DateTime date ;
    DateTime dtVal;
    // string abcd contains 11/22/2019 00:00:00
      abcd = date.ToString("MM/dd/yyyy hh:mm:ss", CultureInfo.InvariantCulture);
    if (DateTime.TryParseExact(abcd, "MM/dd/yyyy hh:mm:ss", System.Globalization.CultureInfo.InvariantCulture, DateTimeStyles.None, out converteddate))
     dtVal = converteddate;   // I am getting 22/11/2019 12:00:00

    I want the dtval value to hold the datetime value as  - 11/22/2019 00:00:00

    How to achieve this ?

    Monday, April 6, 2020 6:29 AM

All replies

  • User-1330468790 posted

    Hi venkatzeus,


    Actually, what you have got in debugger is a string in format "dd/MM/yyyy hh:mm:ss" which is from an implicit transform with the ToString() method of the DateTime .

    The DateTime instance does not have a format. It just a data structure which we used to store the value representing date and time.

    The DateTime instance "dtVal" can be transformed to any format of string as long as you provide a format.  


    You already got the correct value of the date and time so that you don't need to do anything but store it directly to wherever you want.

    Only if you want to display the value of the DateTime instance, you have to consider the format stuff. 


    In your case, if you want to display the DateTime value, you could refer to Custom date and time format strings

    For example: 

    string dateTime = dtVal.ToString("MM/dd/yyyy hh:mm:ss");  // This will give you a string like "11/22/2019 00:00:00"

    Otherwise, there is nothing to do with the DateTime instance "dtVal". 


    Hope this can help you.

    Best regards,


    Tuesday, April 7, 2020 1:54 AM