The problem:
I have A LOT of code that in many places assumes a local time, and uses the function DateTime.FromFileTime
.
Now, some of our Data services have switched to UTC time, and I want to know if there is a way to convert UTC time to local time?
In both cases, all I have is a long, which is the windows file time. If I use the FromFileTimeUtc
function, the value I output is accurate, if I don't then it's wrong.
I don't want to change all my code where it says FromFileTime
to FromFileTimeUtc
. Instead, I have a transformation layer where I'll do this conversion.
Any ideas?
var utcDateTime = DateTime.UtcNow;
var localDateTime = TimeZone.CurrentTimeZone.ToLocalTime(utcDateTime);
[EDIT] To answer your comment: 'looking to change the long value that is passed into DateTime.FromFileTimeUtc .. such that it gives the same value when passed into DateTime.FromFileTime'
private static long ConvertFileTimeToLocalTime(long fileTime)
{
return fileTime + ((long)TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now).TotalMilliseconds * 10000);
}
Test:
var fileTime = DateTime.Now.ToFileTime();
var wrongTime = DateTime.FromFileTimeUtc(fileTime);
var correctTime = DateTime.FromFileTimeUtc(ConvertFileTimeToLocalTime(fileTime));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With