Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# convert datetimeoffset to string with milliseconds

The default toString() method in datetimeoffset converts the time into string format but loses the milliseconds. Is there anyway to preserve it?

like image 687
Yang Avatar asked Mar 23 '11 16:03

Yang


4 Answers

ToString() takes a format argument. There are existing string format codes that will print milliseconds - take a look at the list here.

For example the format code "o" will print a full time string with milliseconds, or you can create your own format string to match your needs and use the "ffff" specifier to add milliseconds where appropriate.

myDateTime.ToString("o")
like image 73
womp Avatar answered Nov 18 '22 20:11

womp


You have to use "ffff" in the string format to get miliseconds, like:

DateTime date = DateTime.Now;
 string strDate = String.Format("{0:dd.MM.yyyy hh:mm.ss:ffff}", date);

Mitja

like image 32
Mitja Bonca Avatar answered Nov 18 '22 21:11

Mitja Bonca


According to the documentation of DateTimeOffset this behaves in most ways similar to ToString of the DateTime class. This means that you can for example use the standard format string o which shows the milliseconds, or you can use whatever custom format pattern you want.

So you can do this:

Console.WriteLine(dto.ToString("o"));
like image 3
steinar Avatar answered Nov 18 '22 20:11

steinar


You can do this using the f character in your format string.

DateTimeOffset.Now.ToString("ddMMyyy-HH:mm:ss")

Gives "23032011-16:58:36"

DateTimeOffset.Now.ToString("ddMMyyy:HHmmssffff")

Gives "23032011-16:59:088562"

like image 2
Swaff Avatar answered Nov 18 '22 20:11

Swaff