在 C# 中将日期时间转换为显示毫秒
我想显示毫秒,但 ToString 将毫秒显示为 00000。
我提供下面的代码,以及每个步骤的输出。
String currentDateTime = DateTime.Now.ToString("G");
输出 - 7/27/2011 3:05:31 PM
System.DateTime dateTime = System.DateTime.Parse(currentDateTime);
输出 - 7/27/2011 3:05:31 PM
String dateTimeStr = dateTime.ToString("hh. mm.ss.ffffff", "en-US");
输出 - 03.05.32.000000
我想用毫秒显示输出,例如 03.05.32.33456
如果我使用 ParseExact 而不是 Parse,则会出现异常。我知道我可以使用 TryParseExact,但该解决方案可能不合适,因为我需要针对此问题的通用解决方案。
有人可以帮助我吗?
提前致谢。 苏杰
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");
Output - 7/27/2011 3:05:31 PM
System.DateTime dateTime = System.DateTime.Parse(currentDateTime);
Output - 7/27/2011 3:05:31 PM
String dateTimeStr = dateTime.ToString("hh.mm.ss.ffffff", "en-US");
Output - 03.05.32.000000
I want to show the output with the milliseconds , eg 03.05.32.33456
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 .
Can someone help me in this.
Thanks in advance.
Sujay
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不确定您为什么要从 DateTime 迁移 ->字符串 ->日期时间
这应该显示毫秒
如果您没有在这些行中查找其他信息,请编辑帖子
Not sure why you are moving from DateTime -> string -> DateTime
This should display milliseconds
Please edit the post if you are not looking on these lines for additional info
通过使用您之前从字符串构建的相同 dateTime 对象(“7/27/2011 3:05:31 PM”,没有任何毫秒),您将丢失毫秒。
如果您直接将 Now 转换为字符串,则不会丢失毫秒:
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.
If you were to convert Now to a string directly, you would not lose the milliseconds:
在代码中,您首先使用标准“G”格式将 DateTime 序列化为字符串,该格式没有毫秒。当然,稍后当你解析这个字符串时,你会得到 000000:
In your code you first serialize the DateTime to string using the standard "G" format, which doesn't have miliseconds. So sure, you get 000000 later when you parse this string back: