Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - DateTime.FromFileTimeUtc to DateTime.FromFileTime

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?

like image 309
Guruprasad Nilam Avatar asked Jun 19 '11 06:06

Guruprasad Nilam


1 Answers

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));
like image 97
Alex Aza Avatar answered Oct 12 '22 23:10

Alex Aza