ASP.NET membership returning DateTime with Kind set to Local

I have an MVC3 project using ASP.NET default membership provider. I am trying to show the details of a user on a View page. When I do

MembershipUser user = Membership.GetUser(id);

to get the user I am about to display, all of the DateTimes (CreationDate, LastActivityDate) have the Kind property set to Local.

All of these dates are saved in the SQL Server database in UTC time, so why are they coming into MVC as Local? It is messing up my time zone conversions because I expect the server times to be in UTC.

Is there something you can set so that the user returned from the GetUser function will have DateTimes in DateTimeKind.Utc?


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();
链接地址: http://www.djcxy.com/p/46638.html

上一篇: 将ISO8601转换为DateTime并保留时区信息

下一篇: 将Kind设置为本地的ASP.NET成员资格返回DateTime