我将日期时间存储到数据库中,然后检索值。我的服务器数据库位于其他国家/地区。因此,当检索值时,它将采用其他国家/地区的日期和时间。
我在控制器中尝试如下,
if (item.CreatedDate == null)
{
item.CreatedDate = DateTime.Now;
var timeZone = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(item.CreatedDate, TimeZoneInfo.Local.Id, item.CreatedDate.Value).ToString();
}
我在这里遇到线路错误...如何纠正?
传递的值甚至不是正确的数据类型。 阅读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,并且始终包含一个值。