开发者

Converting the date time to display milliseconds in C#

I want to show the milliseconds, but ToString shows t开发者_运维技巧he milliseconds as 00000.

I am providing the code below, with the output at each step.

  1. String currentDateTime = DateTime.Now.ToString("G");

    Output - 7/27/2011 3:05:31 PM

  2. System.DateTime dateTime = System.DateTime.Parse(currentDateTime);

    Output - 7/27/2011 3:05:31 PM

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


Not sure why you are moving from DateTime -> string -> DateTime This should display milliseconds

DateTime dt = DateTime.Now;
dt.ToString("hh:mm:ss.fff") 

Please edit the post if you are not looking on these lines for additional info


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:

String dateTimeStr = DateTime.Now.ToString("hh.mm.ss.ffffff", "en-US");


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:

        String currentDateTime = DateTime.Now.ToString("G");
        Console.WriteLine(currentDateTime);

        System.DateTime dateTime = System.DateTime.Parse(currentDateTime);

        Console.WriteLine(dateTime.ToString("hh.mm.ss.ffffff"));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜