I am trying to convert microseconds to DateTime. Please find the code below,
long microSecs = 1632489907280; // Working
long microSecs = 1650391805000000 // Not working -- It has nanoseconds also.
DateTimeOffset utc = DateTimeOffset.FromUnixTimeMilliseconds(microSecs).UtcDateTime;
return utc.ToString("yyyy-MM-ddTHH:mm:ss.fffZ");
Anyone help me to resolve the issue?
CodePudding user response:
Try using the following format:
yyyy-MM-ddTHH:mm:ss.ffffffZ
The format .fff
is for milliseconds. Your example 1632489907280
is also in milliseconds, so it works fine. But the other case, instead of milliseconds is in microseconds, so the former format does not work anymore. You need 6 f
symbols to deal with microseconds.
CodePudding user response:
why first input is working and second input is not working?
There is no built-in method from DateTime
class to process epoc microseconds
In your first example, 1632489907280
is within the milliseconds
range, so DateTimeOffset.FromUnixTimeMilliseconds()
considering 1632489907280
as milliseconds not microseconds.
In your second case, 1650391805000000
is greater than the max range of milliseconds.
From MSDN Documentation, DateTime.FromUnixTimeMilliseconds(milliseconds)
throws an ArgumentOutOfRangeException
if the
milliseconds is less than -62,135,596,800,000.
-or-
milliseconds is greater than 253,402,300,799,999.
To fix the error, convert your microseconds to milliseconds and then pass it to DateTime.FromUnixTimeMilliseconds(milliseconds)
.
Try below code,
public static string ProcessEpocTime(long microSecs)
{
//Convert microseconds to Milliseconds.
long milliSecs = (long)microSecs / 1000;
DateTimeOffset utc = DateTimeOffset.FromUnixTimeMilliseconds(milliSecs).UtcDateTime;
return utc.ToString("yyyy-MM-ddTHH:mm:ss.fffZ");
}
Note: This solution will work for valid microseconds value.