-2

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

我在控制器中尝试如下,

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

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

4

1 回答 1

2

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

另请阅读:

还要了解这里的某个地方实际上您必须知道用户的时区。只是调用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?(可为空的日期时间)。对这些领域这样做是没有意义的。它们在您的数据库中应该是非空的,并且始终包含一个值。

于 2013-09-14T07:26:59.033 回答