Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting the date time to display milliseconds in C#

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

like image 480
Sujay Ghosh Avatar asked Jul 27 '11 09:07

Sujay Ghosh


2 Answers

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

like image 56
V4Vendetta Avatar answered Sep 18 '22 22:09

V4Vendetta


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");
like image 23
msergeant Avatar answered Sep 19 '22 22:09

msergeant