且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在c#中将字符串转换为24小时格式的日期时间

更新时间:2023-11-07 18:43:46

DateTime 类型 [ ^ ]没有格式。该值存储为ticks的数量(100公元0001年1月1日午夜(公元前1月1日午夜)。



你看到的是调试器对该值的表示,它转换了 DateTime 使用标准格式的字符串。



显示 DateTime 对用户来说,你可以使用标准 [ ^ ]或自定义 [ ^ ]格式化字符串以任何方式显示它。
The DateTime type[^] does not have a format. The value is stored as the number of "ticks" (100 nanoseconds) since midnight, January 1, 0001 A.D. (C.E.) in the Gregorian calendar.

What you are seeing is the debugger's representation of that value, which converts the DateTime to a string using a standard format.

When you display the DateTime to the user, you can use the standard[^] or custom[^] format strings to display it any way you want.


字符串 - 我得到格式异常,因为YYYY不是已知的格式代码:它应该是:

String - I get a Format Exception, because "YYYY" is not a known format code: it should be:
String strDate = "24/01/2013 00:00:00";
DateTime date = DateTime.ParseExact(strDate, "dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture);
Console.WriteLine(date);

这给了我:

Which gives me:

24/01/2013 00:00:00



我怀疑你的输出是将数据格式化为12小时(AM / PM)格式:


I suspect your output is formatting the data to 12 hour (AM/PM) format instead:

Console.WriteLine(date.ToString("dd/MM/yyyy hh:mm:ss"));

所以试试:

So try:

Console.WriteLine(date.ToString("dd/MM/yyyy HH:mm:ss"));



这可能会误导你。


Which might be misleading you.


成功解析成 DateTime 结构,您可以使用.NET字符串格式以您想要的格式显示它。



自定义日期和时间格式 [ ^ ]



Once you have successfully parsed into a DateTime structure, you can use the .NET string formatting to display it in the format you want.

Custom Date and Time Formatting[^]

String strDate = "24/01/2013 00:00:00"
String strDate = "01/24/2013 00:00:00";

DateTime date = DateTime.Parse(strDate);

Console.WriteLine("My Date: {0:dd/MM/yyyy HH:mm:ss}", date);