在C#中将日期时间转换为显示毫秒 [英] Converting the date time to display milliseconds in C#

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

问题描述

我想显示毫秒,但是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.

  1. 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

字符串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 .

有人可以帮我吗?

先谢谢了.Sujay

Thanks in advance. Sujay

推荐答案

通过使用先前从字符串("7/27/2011 3:05:31 PM",不带任何毫秒)构建的相同dateTime对象,您失去了毫秒.

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#中将日期时间转换为显示毫秒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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