Search code examples
c#stringdatetimedate-format

c# convert string to DateTime format


I am reading a string value from DataTable which is in the format :

"3/29/2022 6:32:05 PM"

How do I convert this string in this format:

"03292022"

I tried this:

string format= "MMddyyyy";
string dateString =  "3/29/2022 6:32:05 PM";
DateTime dateValue;

if (DateTime.TryParseExact(dateString, format,
                           CultureInfo.InvariantCulture,
                           DateTimeStyles.None,
                           out dateValue))
   Console.WriteLine("Converted '{0}' to {1}.", dateString, dateValue);
else
   Console.WriteLine("Unable to convert '{0}' to a date.", dateString);

Solution

  • Here is a working example

    string input = "3/29/2022 6:32:05 PM";
    string output = DateTime.Parse(input).ToString("MMddyyyy");
    
    Console.WriteLine(output);  
    

    You can use DateTime.Parse method to parse the input string into a DateTime object, and then use the ToString method to format the DateTime object as a string with the format "MMddyyyy".

    More details can be found here

    https://docs.microsoft.com/en-us/dotnet/api/system.datetime.tostring#remarks