'String was not recognized as a valid DateTime.' RRS feed

  • Question

  • I am trying to get datetime including time part from the string variable

    string dateString = dt.ToString("yyyy-MM-dd HH:mm:ss.FFF"); 
    datetime dt = DateTime.ParseExact(dateString, "dd/MM/yyyy HH:mm", CultureInfo.InvariantCulture);

    the value of datestring is "2019-06-19 02:15:00"

    when I parse the datestring  into dt the folllowing error is coming 

    'String was not recognized as a valid DateTime.'

    Please can you help to fix the error




    Tuesday, July 9, 2019 10:24 AM

All replies

  • Hello,

    Given what you have presented I get the proper result (with or without the fff.

    var dateTime = new DateTime(2019,6,19,2,15,0);
    var text = dateTime.ToString("MM/dd/yyyy HH:mm:ss.fff",

    06/19/2019 02:15:00.000

    var dateTime = new DateTime(2019,6,19,2,15,0);
    var text = dateTime.ToString("MM/dd/yyyy HH:mm:ss",
    06/19/2019 02:15:00

    var dateTime = new DateTime(2019,6,19,2,15,0);
    var text = dateTime.ToString("dd/MM/yyyy HH:mm:ss",

    19/06/2019 02:15:00

    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    profile for Karen Payne on Stack Exchange

    Tuesday, July 9, 2019 11:14 AM
  • When parsing a string to datetime you have to specify the correct (date)format of the string:

    var dateString = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.FFF"); 
    var dt = DateTime.ParseExact(dateString, "yyyy-MM-dd HH:mm:ss.FFF", CultureInfo.InvariantCulture);

    Tuesday, July 9, 2019 12:03 PM
  • Hi polachan, 

    Thank you for posting here.

    I have made a test on my side and reproduced your problem:

    As Christoph Biegner suggested, in ParseExact() method, the format of the string representation must match the specified format exactly.

    The format of ‘dataString’ does not match the format ‘dd/MM/yyyy HH:mm’, so try to change the format to ‘yyyy-MM-dd HH:mm:ss’.

    Here’s the code:

                string dateString = "2019-06-19 02:15:00";
                //var dt = DateTime.ParseExact(dateString, "dd/MM/yyyy HH:mm", CultureInfo.InvariantCulture);
                var dt = DateTime.ParseExact(dateString, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);


    Best Regards,

    Xingyu Zhao

    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Wednesday, July 10, 2019 3:22 AM