在 ASP.NET MVC2 中,转换时间用户的时区.如何获取时区信息

本文关键字:时区 何获取 信息 获取 用户 MVC2 NET ASP 时间 转换 | 更新日期: 2023-09-27 18:31:12

我将日期时间存储到数据库中,然后检索值。我的服务器数据库位于其他国家/地区。因此,当检索值时,它将采用其他国家/地区的日期和时间。

我在控制器中尝试如下,

 if (item.CreatedDate == null)
        {
            item.CreatedDate = DateTime.Now;
            var timeZone = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(item.CreatedDate, TimeZoneInfo.Local.Id, item.CreatedDate.Value).ToString();
        }

我在这里遇到线路错误...如何纠正?

在 ASP.NET MVC2 中,转换时间用户的时区.如何获取时区信息

传递的值甚至不是正确的数据类型。 阅读TimeZoneInfo,以便您知道如何正确使用它。

另请参阅:

  • 为什么不应该使用DateTime.Now
  • 时区标签维基
  • 夏令时和时区最佳做法

还要了解,在这里的某个地方,您实际上必须知道用户的时区。 仅调用TimeZoneInfo.Local.Id是行不通的,因为这也是服务器的时区。 MVC 没有魔法来了解用户的时区。 你必须向他们询问,或者采用其他涉及JavaScript的策略。

从您的评论来看,您似乎正在寻找这样的东西:

// These should be stored in UTC.  Do not store them in anyone's local time.
item.CreatedDate = DateTime.UtcNow;
item.UpdatedDate = DateTime.UtcNow;
// Then later when you want to convert to a specific time zone, do this
string timeZoneId = "India Standard Time"; // as an example
TimeZoneInfo timeZone = TimeZoneInfo.FindSystemTimeZoneById(timeZoneId);
DateTime localCreated = TimeZoneInfo.ConvertTimeFromUtc(item.CreatedDate, timeZone);
DateTime localUpdated = TimeZoneInfo.ConvertTimeFromUtc(item.UpdatedDate, timeZone);

此外,您似乎正在对属性使用DateTime?(可为空的日期时间)。 对这些字段这样做是没有意义的。 它们在数据库中应为非 null,并且始终包含一个值。