1

我有一个使用 ASP.NET 默认成员提供程序的 MVC3 项目。我正在尝试在查看页面上显示用户的详细信息。当我做

MembershipUser user = Membership.GetUser(id);

为了让我将要显示的用户,所有的 DateTimes(CreationDate、LastActivityDate)都将 Kind 属性设置为 Local。

所有这些日期都以 UTC 时间保存在 SQL Server 数据库中,那么为什么它们会作为 Local 进入 MVC?它弄乱了我的时区转换,因为我希望服务器时间是 UTC。

是否可以设置一些内容,以便从 GetUser 函数返回的用户在 DateTimeKind.Utc 中具有 DateTimes?

4

1 回答 1

1

Just use myDate.ToUniversalTime()

If you mean that the value in your DateTime is actually the UTC time, but the kind is set to Local, then you will have to convert it to UTC.

var myUtcDate = DateTime.SpecifyKind(myDate, DateTimeKind.Utc);

Unfortunately, this is a general problem with the .NET DateTime class and SQL, not anything specific to MVC. I don't know of any way to get the DateTime in UTC format with DateTimeKind.Utc set.

You may want to read John Skeets rant about DateTime.

http://noda-time.blogspot.com/2011/08/what-wrong-with-datetime-anyway.html

If you need to use this frequently, one option would be to create an extension method to do this.

public static class DateTimeExtensions {
    public static DateTime MakeUtcKind(this DateTime dateTime) {
        return DateTime.SpecifyKind(dateTime, DateTimeKind.Utc);
    }
}

Then you can simply do this:

var createDate = Membership.GetUser(id).CreationDate.MakeUtcKind();
于 2013-05-29T19:45:56.243 回答