Home > database >  c# convert string to DateTime format
c# convert string to DateTime format

Time:12-17

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);

CodePudding user response:

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

CodePudding user response:

You must first parse the date from the original format:

if (DateTime.TryParseExact(dateString, "M/dd/yyyy h:mm:ss tt",
                           CultureInfo.InvariantCulture,
                           DateTimeStyles.None,
                           out dateValue))

The "Exact" in ParseExact() isn't just for show: the format string here must be perfect, including single vs double letters for date parts like month, as well as upper-case vs lower-case for date parts like hour. In spite of this, it's usually preferrable to provide the format for ParseExact() over the easier Parse(), which opens you up issues around inferring the cultural settings.

Then you can output the date in the desired format:

Console.WriteLine($"Converted '{dateString}' to {dateValue:MMddyyyy}.");

Remember DateTime values themselves do not have any human-readable format, so you have to specify the format again every time you output it or convert it back to a string. Also remember cultural/internationalization issues mean these conversions are far slower and more error-prone than you'd expect: something to avoid.

  • Related