C # convert datetimeoffset to string with milliseconds

The toString () method by default in datetimeoffset converts time to string format, but loses milliseconds. Is there any way to save it?

+8
c # datetime datetimeoffset
source share
4 answers

ToString() takes a format argument. There are existing string format codes that will print milliseconds - see here.

For example, the format code โ€œoโ€ will print the complete time line with milliseconds, or you can create your own format string to suit your needs and use the โ€œffffโ€ specifier to add milliseconds where necessary.

 myDateTime.ToString("o") 
+19
source share

You must use "ffff" in string format to get miliseconds, for example:

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

Mitya

+6
source share

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

So you can do this:

 Console.WriteLine(dto.ToString("o")); 
+3
source share

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"

+2
source share

All Articles