In ASP.NET MVC2, convert time user's timezone.

2019-09-24 10:53发布

I stored datetime into database then i retrieve the values.. My server db is located other country. so when the value is retrieve it is taking other country date and time..

I tried in controller as follow,

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

I got line error here... How to correct it?

1条回答
看我几分像从前
2楼-- · 2019-09-24 11:19

You're passing values that aren't even of the right data type. Read up on TimeZoneInfo so you know how to use it properly.

Also read:

Also understand that somewhere here you actually have to know the user's time zone. Just calling TimeZoneInfo.Local.Id isn't going to work, because that is also the server's time zone. There's no magic performed by MVC to know the time zone of your user. You'll have to ask them for it, or employ some other strategy involving JavaScript.

From your comments, it appears you are looking for something like this:

// 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);

Also, it seems like you might be using DateTime? (nullable datetimes) for your properties. It doesn't make sense to do that for these fields. They should be non-null in your database and always contain a value.

查看更多
登录 后发表回答