C# - DateTime.FromFileTimeUtc 到 DateTime.FromFileTime

发布于 2024-11-16 06:40:44 字数 360 浏览 1 评论 0原文

问题:

我有很多代码,在很多地方都假定本地时间,并使用函数 DateTime.FromFileTime

现在,我们的一些数据服务已经切换为UTC时间,我想知道是否有办法将UTC时间转换为本地时间?

在这两种情况下,我所拥有的只是很长的时间,即 Windows 文件时间。如果我使用 FromFileTimeUtc 函数,我输出的值是准确的,如果我不使用,那么它是错误的。

我不想将 FromFileTime 更改为 FromFileTimeUtc 的所有代码。相反,我有一个转换层,我将在其中进行此转换。

有什么想法吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

娇柔作态 2024-11-23 06:40:44
var utcDateTime = DateTime.UtcNow;
var localDateTime = TimeZone.CurrentTimeZone.ToLocalTime(utcDateTime);

[编辑]回答您的评论:“希望更改传递给 DateTime.FromFileTimeUtc 的长值..,以便在传递给 DateTime.FromFileTime 时给出相同的值”

private static long ConvertFileTimeToLocalTime(long fileTime)
{
    return fileTime + ((long)TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now).TotalMilliseconds * 10000);
}

测试:

var fileTime = DateTime.Now.ToFileTime();

var wrongTime = DateTime.FromFileTimeUtc(fileTime);

var correctTime = DateTime.FromFileTimeUtc(ConvertFileTimeToLocalTime(fileTime));
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));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文