如何在c#中更改datetime的格式 [英] how to change the format of datetime in c#
本文介绍了如何在c#中更改datetime的格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个表格,上面有计时器工具来显示当前的日期和时间。时间格式为12/05/2014 12:17:20但我希望它能在2014年5月12日星期五12:17:20。请有人告诉我如何在c#中执行此操作。
解决方案
如果您将DateTime
转换为string
,然后你可以使用这种格式:
string formatted = dt.ToString( ddd dd MMM yyyy hh:mm:ss); // 将'dt'更改为DateTime的名称
首先 - DateTime以二进制形式存储它的值,独立于可视化表示(格式),但它有一个ToString()方法,可以根据需要格式化值:http://msdn.microsoft.com/en-us/library/zdtaw1bw(v=vs。 110).aspx [ ^ ]
如果您的日期时间为字符串格式,如12/05/2014 12:17:20,那么最好将其转换为DateTime类型。可以通过提供我们需要的格式将DateTime转换为字符串格式。
用于String to DateTime转换使用DateTime.ParseExact [ ^ ]或 DateTime.TryParseExact [ ^ ]方法
如果有DateTime对象,请根据需要使用自定义格式字符串调用ToString方法。检查自定义日期和时间格式字符串 [ ^ ]了解更多信息。
示例代码:
DateTime dt = DateTime.ParseExact(< span class =code-string> 12/05/2014 12:17:20, MM / dd / yyyy hh:mm:ss,CultureInfo.InvariantCulture);
string result = dt.ToString( dd MMM yyyy hh:mm:ss);
i have a form which has timer tool on it to display the current date and time. the time is in the format 12/05/2014 12:17:20 but i want it to be in Fri 12 May 2014 12:17:20. please can someone tell me how to do that in c#.
解决方案
If you convert yourDateTime
to astring
, then you can use this format:
string formatted = dt.ToString("ddd dd MMM yyyy hh:mm:ss"); // change 'dt' into the name of your DateTime
First of all - DateTime stores it's value in binary and independent of visual representation (format), however it has a ToString() method, that can format the value as you wish: http://msdn.microsoft.com/en-us/library/zdtaw1bw(v=vs.110).aspx[^]
if you have datetime in string format like "12/05/2014 12:17:20" then better convert this to a DateTime type. DateTime can be convert to string format by giving the format which we needed.
for the String to DateTime conversion use DateTime.ParseExact[^] or DateTime.TryParseExact[^] methods
When you have the DateTime object, call the ToString method with custom format string as you need. Check Custom Date and Time Format Strings[^] for more information.
Sample code:
DateTime dt = DateTime.ParseExact("12/05/2014 12:17:20", "MM/dd/yyyy hh:mm:ss", CultureInfo.InvariantCulture); string result =dt.ToString("dd MMM yyyy hh:mm:ss");
这篇关于如何在c#中更改datetime的格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文