In ASP.NET MVC2, convert time user's timezone. How to get timezone info? [closed]

南楼画角 提交于 2019-12-13 22:31:48

问题


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:


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:

  • Why you shouldn't use DateTime.Now
  • The timezone tag wiki
  • DST and Time Zone Best Practices

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.



来源:https://stackoverflow.com/questions/18798913/in-asp-net-mvc2-convert-time-users-timezone-how-to-get-timezone-info

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!