如何在 C# 中转换日期时间格式?

How do I convert dateTime format in C#?

这是

string date = "07-Feb-2020"; 

我不确定如何将其转换为

"2020-02-07 00:00:00"

代表

您必须先将字符串解析为 DateTime。然后你可以做 ToString("yyyy-MM-dd HH:mm:ss")

ParseExactDateTime 然后格式化为所需的 string 表示:

  string date = "07-Feb-2020";

  string result = DateTime
    .ParseExact(date, "dd-MMM-yyyy", CultureInfo.InvariantCulture)
    .ToString("yyyy-MM-dd HH:mm:ss");

使用精确解析

DateTime.ParseExact(date, "dd-MMM-yyyy", null);

使用日期时间:

 DateTime thisDate1 = new DateTime(2011, 6, 10);
 Console.WriteLine("Today is " + thisDate1.ToString("MMMM dd, yyyy") + ".");

 DateTimeOffset thisDate2 = new DateTimeOffset(2011, 6, 10, 15, 24, 16, 
                                          TimeSpan.Zero);
 Console.WriteLine("The current date and time: {0:MM/dd/yy H:mm:ss zzz}", 
               thisDate2); 
 // The example displays the following output:
 //    Today is June 10, 2011.
 //    The current date and time: 06/10/11 15:24:16 +00:00

Code is from Microsoft docs

您可以创建任何格式