5

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");

    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

Community
  • 1
  • 1
Sujay Ghosh
  • 2,670
  • 6
  • 27
  • 40

3 Answers3

7

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

V4Vendetta
  • 34,000
  • 7
  • 73
  • 81
6

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");
msergeant
  • 4,701
  • 3
  • 23
  • 25
3

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"));
Petar Ivanov
  • 84,604
  • 7
  • 74
  • 90
  • Peter - Please see the output of 3. I had also used dateTime.ToString("hh.mm.ss.ffffff", "en-US"); , but I get a wrong output. The millisecond are 0000. – Sujay Ghosh Jul 27 '11 at 10:02
  • Are you talking about the serialization , yes I did . I want the output without serialization. – Sujay Ghosh Jul 27 '11 at 10:13