问题描述
我想显示毫秒,但 ToString 显示毫秒为 00000.
I want to show the milliseconds, but ToString shows the milliseconds as 00000.
我提供下面的代码,以及每一步的输出.
I am providing the code below, with the output at each step.
String currentDateTime = DateTime.Now.ToString("G");
输出 - 2011 年 7 月 27 日下午 3:05:31
Output - 7/27/2011 3:05:31 PM
System.DateTime dateTime = System.DateTime.Parse(currentDateTime);
输出 - 2011 年 7 月 27 日下午 3:05:31
Output - 7/27/2011 3:05:31 PM
String dateTimeStr = dateTime.ToString("hh.mm.ss.ffffff", "en-US");
输出 - 03.05.32.000000
Output - 03.05.32.000000
我想用毫秒显示输出,例如 03.05.32.33456
I want to show the output with the milliseconds , eg 03.05.32.33456
如果我使用 ParseExact 而不是 Parse,我会遇到异常.我知道我可以使用 TryParseExact,但那个解决方案可能不合适,因为我需要一个通用的解决方案来解决这个问题.
If I used ParseExact instead of Parse, I am getting an exception. I know that I can use TryParseExact, but that solution might not be suitable , as I need a generic solution to this problem .
谁能帮帮我.
提前致谢.苏杰
推荐答案
通过使用之前从字符串构建的相同 dateTime 对象(7/27/2011 3:05:31 PM"没有任何毫秒),您'正在失去毫秒.
By using the same dateTime object that you previously built from a string ("7/27/2011 3:05:31 PM" without any milliseconds), you're losing the milliseconds.
如果您直接将 Now 转换为字符串,则不会丢失毫秒数:
If you were to convert Now to a string directly, you would not lose the milliseconds:
String dateTimeStr = DateTime.Now.ToString("hh.mm.ss.ffffff", "en-US");
这篇关于在 C# 中将日期时间转换为显示毫秒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!