Formatting Strings In C# RRS feed

  • Question

  • I am pulling data and have two variables d1 (date in yyyymmdd format) and t1 (time in 24 hour format).  I want to format both of the strings so that d1 is in a mm/dd/yyyy format and t1 is in "American" time (so 17:10:00 = 5:10 PM).  

    Then once the strings have been formatted I want to print them so they display together like

    Console.WriteLine(The date and time are as follows: " + d1 + " " + t1);

    And the output you would see is : 01/07/2016 10:42 AM

    This is the syntax I am using to extract the values:

    foreach (var info in xml.Descendants("Parent"))
    	d1 = (string)parent.Descendants("POD").FirstOrDefault();
    	t1 = (string)parent.Descendants("TOD").FirstOrDefault();

    And I have tried

    DateTime dt = DateTime.ParseExact(d1, "MM/dd/yyyy", CultureInfo.InvariantCulture);
    var customdt = dt.ToString("MM/dd/yyyy");

    Which throws an error of:

    An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll

    Additional information: String was not recognized as a valid DateTime.

    What do I need to do to format my strings as needed?

    *To Sum It Up*- 

    format d1 As mmddyyyy = 01/07/2016

    format t1 As HH:MM = 10:48

    Then combine the strings so output is

    The date and time is: 01/07/2016 10:48

    C# using Visual Studio 2015

    Saturday, January 7, 2017 3:48 PM


  • When d1 = "20170107" then you need to parse it as follows:

    DateTime dt = DateTime.ParseExact(d1, "yyyyMMdd", CultureInfo.InvariantCulture);
    var customdt = dt.ToString("MM/dd/yyyy", CultureInfo.InvariantCulture);

    The second argument of ParseExact is the exact format of the input string you want to parse.


    • Marked as answer by IndigoMontoya Saturday, January 7, 2017 5:06 PM
    Saturday, January 7, 2017 4:28 PM