如何将具有这种格式 (yyyy-MM-dd HH:mm:ss) 的字符串形式的日期转换为这种格式 (dd-MM-yyyy HH:mm:ss) 的 DateTime 对象

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)

我目前正在使用 C#,我想将“2022-01-15 18:40:30”之类的字符串转换为格式为“15-01-2022 18:40:30”的 DateTime 对象.下面是我试过的。

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

但我一直得到的结果是“2022-01-15T18:40:30”

如有任何帮助,我们将不胜感激

DateTime 对象本身没有特定的“格式”。

字符串表示在您调用 .ToString() 函数时创建。

有多个 overloads 的 ToString 函数可以指定格式。

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

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

试试这个风格

试试这个:

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

正如其他人所指出的,您有 DateTime 的内部数据值。

因此,我们当然建议您将字符串转换为该内部格式。

完成后,您就可以自由地将内部日期时间值输出为您想要的任何格式和输出。

因此,我们有这个:

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

输出是这样的: