将字符串转换为日期时间,格式为yyyy-MM-dd HH:mm:ss in C#

dan*_*arj 9 c# datetime

我怎么能把它转换2014-01-01 23:00:00DateTime我这样做的:

Console.WriteLine(DateTime.ParseExact("2014-01-01 23:00:00", "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture));
Run Code Online (Sandbox Code Playgroud)

结果是这样的:

1/1/2014 11:00:00 PM
Run Code Online (Sandbox Code Playgroud)

这件事让我抓狂,因为这种格式在java中运行.

Plu*_*lue 17

我认为你的解析工作.问题是转换回字符串时.您可以在参数中提供所需的格式:

DateTime date = DateTime.ParseExact("2010-01-01 23:00:00", "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
string formattedDate = date.ToString("yyyy-MM-dd HH:mm:ss")
Console.WriteLine(formattedDate);
Run Code Online (Sandbox Code Playgroud)

默认情况下(没有指定的格式),它使用从当前文化派生的格式信息.


D S*_*ley 6

因为2014-01-01 23:00:00是IS 2014-01-01 11:00:00 PM

更好的解释

您在隐式调用DateTime.ToString(),默认情况下使用的是General("G")格式,在en-US区域性中为 MM/dd/yyyy hh:mm:ss tt

如果要以其他格式显示时间,则需要指定时间:

string s = DateTime.ParseExact("2010-01-01 23:00:00", "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
Console.WriteLine(s.ToString("yyyy-MM-dd HH:mm:ss");
Run Code Online (Sandbox Code Playgroud)

或者由于您使用的是相同的格式字符串,只需存储它:

string format = "yyyy-MM-dd HH:mm:ss";
DateTime dt = DateTime.ParseExact("2010-01-01 23:00:00", format , CultureInfo.InvariantCulture);
Console.WriteLine(s.ToString(format);
Run Code Online (Sandbox Code Playgroud)