c# - 将我的 DateTime 转换为 UTC 时遇到问题

标签 c# .net asp.net asp.net-mvc

我将所有日期以 UTC 格式存储在我的数据库中。我向用户询问他们的时区,我想使用他们的时区加上我猜测的服务器时间来为他们计算 UTC。

一旦我有了它,我想使用他们新转换的 UTC 日期进行搜索以查看数据库中的范围。

但我总是得到这个异常(exception)。

System.ArgumentException was unhandled by user code  
Message="The conversion could not be completed because the   
supplied DateTime did not have the Kind property set correctly.  
For example, when the Kind property is DateTimeKind.Local,   
the source time zone must be TimeZoneInfo.Local.  
Parameter name: sourceTimeZone"

我不知道为什么我会得到这个。

我尝试了两种方式

 TimeZoneInfo zone = TimeZoneInfo.FindSystemTimeZoneById(id);
 // I also tried DateTime.UtcNow
 DateTime now = DateTime.SpecifyKind(DateTime.Now, DateTimeKind.Local); 
 var utc = TimeZoneInfo.ConvertTimeToUtc(now , zone );

这失败了,所以我尝试了

 DateTime now = DateTime.SpecifyKind(DateTime.Now, DateTimeKind.Local); 
 var utc = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(now, 
                                           ZoneId, TimeZoneInfo.Utc.Id);

这也因同样的错误而失败。我做错了什么?

编辑这行得通吗?

 DateTime localServerTime = DateTime.SpecifyKind(DateTime.Now, DateTimeKind.Local);
 TimeZoneInfo info = TimeZoneInfo.FindSystemTimeZoneById(id);

 var usersTime = TimeZoneInfo.ConvertTime(localServerTime, info);

 var utc = TimeZoneInfo.ConvertTimeToUtc(usersTime, userInfo);

编辑 2 @Jon Skeet

是的,我只是在想我可能甚至不需要做这一切。时间的东西现在让我很困惑,所以这就是为什么这篇文章可能不像它应该的那样清晰。我永远不知道 DateTime.Now 到底得到了什么(我试图将我的时区更改为另一个时区,但它一直在获取我的本地时间)。

这就是我想要实现的目标:用户来到该网站,添加一些警报并将其保存为 utc(之前是 DateTime.Now,然后有人建议存储所有 UTC)。

因此,在用户访问我的网站之前,根据我的托管服务器的位置,它可能会在第二天出现。因此,如果据说在 8 月 30 日(他们的时间)显示警报,但由于服务器的时差,他们可能会在 8 月 29 日出现并显示警报。

所以我想处理这个问题。所以现在我不确定我是否应该只存储他们的本地时间然后使用这个偏移量的东西?或者只存储 UTC 时间。仅存储 UTC 时间它仍然可能是错误的,因为用户仍然可能会在本地时间思考并且我不确定 UTC 是如何工作的。它仍然可能在不同的时间结束。

编辑3

 var info = TimeZoneInfo.FindSystemTimeZoneById(id)

 DateTimeOffset usersTime = TimeZoneInfo.ConvertTime(DataBaseUTCDate,
                                             TimeZoneInfo.Utc, info);

最佳答案

你需要将Kind设置为Unspecified,像这样:

DateTime now = DateTime.SpecifyKind(DateTime.Now, DateTimeKind.Unspecified);
var utc = TimeZoneInfo.ConvertTimeToUtc(now , zone);

DateTimeKind.Local 表示本地时区,而不是任何其他时区。这就是您收到错误的原因。

关于c# - 将我的 DateTime 转换为 UTC 时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1354516/

相关文章:

c# - .NET 外部通信

c# - HttpClient post 在 c# 中返回错误的请求,在 postman 中工作

c# - 从类或抽象类继承

c# - Entity Framework 5 查询中的错误数据类型

c# - 尝试在 api 启动后运行方法

.net - 为什么即使页面的 EnableSessionState ="False"ASP.NET 仍然访问状态服务器,但仅适用于 VB.NET 站点,而不适用于 C# 站点?

c# - system.web.ui.webcontrols.textbox不包含 "lines"的定义

c# - Azure 服务总线连续 WebJob 暂停

c# - 在 session 中存储登录名和密码哈希是否安全?

c# - C#中的类和基类继承