在c#中将字符串转换为24小时格式的日期时间 [英] Convert a string to datetime in 24 hour format in c#

查看:222
本文介绍了在c#中将字符串转换为24小时格式的日期时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



如何将字符串转换为24小时格式的日期时间?我尝试了几种方法,但仍然可以获得12小时的格式值。例如:String strDate =24/01/2013 00:00:00

DateTime date = DateTime.ParseExact(strDate,dd / MM / YYYY HH:mm:ss,CultureInfo.InvariantCulture );

但价值是24/01/2013 12:00:00。相反,我需要24/01/2013 00:00:00。请帮忙:(。

Hi,
How to convert a string to datetime in 24 hour format? I have tried several methods but still I get 12 hour format value. Eg: String strDate = "24/01/2013 00:00:00"
DateTime date = DateTime.ParseExact(strDate, "dd/MM/YYYY HH:mm:ss", CultureInfo.InvariantCulture);
But the value is 24/01/2013 12:00:00. Instead I need "24/01/2013 00:00:00". Please help out :(.

推荐答案

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


这篇关于在c#中将字符串转换为24小时格式的日期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆