Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET datetime Millisecond precision issue when converting from string to datetime

Hi. I am trying to convert an incoming datetime value that comes to our system in a string format. It seems that when the precision of milliseconds is higher than 7, the datetime parsing in .NET does not seem to like the value and cannot convert/parse the value. I am a bit stuck on what to do for this? My only current thought is there is a limit on the millisecond size and that anymore precision is not possible? But I want to confirm this is the case rather than assume. Example:

string candidateDateTimeString = "2017-12-08T15:14:38.123456789Z";
if (!success)
        {
            success = DateTime.TryParseExact(trayportDateTimeString, "yyyy-
MM-dd'T'HH:mm:ss.fffffffff'Z'",
                CultureInfo.InvariantCulture, dateTimeStyles, out dateTime);
        }

If I reduce the 'f' values down to just 7, then date time parsing works fine. Is there a limit? Or am I doing something obvious wrong?

like image 472
sridg Avatar asked Dec 09 '17 11:12

sridg


People also ask

How do I get milliseconds from DateTime?

To display the millisecond component of a DateTime value Parse(String) or DateTimeOffset. Parse(String) method. To extract the string representation of a time's millisecond component, call the date and time value's DateTime.

How accurate is DateTime now in C#?

It tends to be between 0.5 and 15 milliseconds.

How are milliseconds represented in date format?

Usually we display time in in 12 hour format hh:mm:aa format (e.g. 12:30 PM) or 24 hour format HH:mm (e.g. 13:30), however sometimes we also want to show the milliseconds in the time. To show the milliseconds in the time we include “SSS” in the pattern which displays the Milliseconds.


2 Answers

According to Custom Date and Time Format Strings docs, 7 is maximum supported digits of second fraction.

like image 192
Andrii Litvinov Avatar answered Sep 24 '22 05:09

Andrii Litvinov


Internally, all DateTime values are represented as the number of ticks (the number of 100-nanosecond intervals) that have elapsed since 12:00:00 midnight, January 1, 0001.

https://msdn.microsoft.com/en-us/library/system.datetime(v=vs.110).aspx

see also: https://docs.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings

like image 25
skyoxZ Avatar answered Sep 22 '22 05:09

skyoxZ