skip to Main Content

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

4

Answers


  1. 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.

    Login or Signup to reply.
  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

    Login or Signup to reply.
  3. Try this one:

    string stringDate = "2022-01-15 18:40:30";
    Console.WriteLine((DateTime.Parse(stringDate)).ToString("dd-MM-yyyy HH:mm:ss"));
    
    Login or Signup to reply.
  4. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search