'How to convert a date in the form of a string with this format (yyyy-MM-dd HH:mm:ss) to a DateTime object of this format (dd-MM-yyyy HH:mm:ss)

I'm currently using C# and I want to convert a string like "2022-01-15 18:40:30" to a DateTime object with this format "15-01-2022 18:40:30". Below is what I've tried.

string stringDate = "2022-01-15 18:40:30";
string newStringDate = DateTime.ParseExact(date, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture).ToString("dd-MM-yyyy HH:mm:ss");

DateTime newDateFormat = DateTime.ParseExact(newStringDate, "dd-MM-yyyy HH:mm:ss", CultureInfo.InvariantCulture);

But the result i keep getting is "2022-01-15T18:40:30"

Any help would be appreciated



Solution 1:[1]

As others pointed out, you have a internal data value for DateTime.

So, FOR SURE we suggest that you convert the string into that internal format.

Once you do that, then you are free to output that internal date time value to ANY kind of format and output you want.

Thus, we have this:

        string stringDate = "2022-01-15 18:40:30";
        DateTime MyDate = DateTime.ParseExact(stringDate,"yyyy-MM-dd HH:mm:ss",CultureInfo.InvariantCulture);

        // now we can output convert to anything we want.
        Debug.Print("Day of week = " + MyDate.ToString("dddd"));
        Debug.Print("Month = " + MyDate.ToString("MM"));
        Debug.Print("Month (as text) = " + MyDate.ToString("MMMM"));

        // desired format
        Debug.Print(MyDate.ToString("dd-MM-yyyy HH:mm:ss"));

And output is this:

enter image description here

Solution 2:[2]

DateTime date = Convert.ToDateTime("2022-01-15");
        DateTime time = Convert.ToDateTime("18:40:30");

        DateTime dt = Convert.ToDateTime(date.ToShortDateString() + " " + time.ToShortTimeString());

try this style

Solution 3:[3]

Try this one:

string stringDate = "2022-01-15 18:40:30";
Console.WriteLine((DateTime.Parse(stringDate)).ToString("dd-MM-yyyy HH:mm:ss"));

Solution 4:[4]

The DateTime object by itself does not have a specific "format".

The string representation gets created when you call the .ToString() function.

There are multiple overloads of the ToString function with which you can specify the format.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Albert D. Kallal
Solution 2 Murat64Bit
Solution 3 Mohi
Solution 4