C # - DateTime.FromFileTimeUtc in DateTime.FromFileTime

Problem:

I have a lot of code that takes local time in many places and uses the DateTime.FromFileTime function.

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 long, this is the Windows file time. If I use the FromFileTimeUtc function, the value I output is accurate if I am not mistaken.

I don't want to change all my code where it says FromFileTime - FromFileTimeUtc . Instead, I have a transform layer where I will do this transform.

Any ideas?

+6
source share
1 answer
 var utcDateTime = DateTime.UtcNow; var localDateTime = TimeZone.CurrentTimeZone.ToLocalTime(utcDateTime); 

[EDIT] To answer your comment: โ€œwant to change the long value that is passed to DateTime.FromFileTimeUtc .. so that it gives the same value when passed to 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)); 
+4
source

Source: https://habr.com/ru/post/890847/


All Articles