Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
107 views
in Technique[技术] by (71.8m points)

c# - How to do timezones in ASP.NET MVC?

On my site, I need to know what timezones people are located in, in order to display messages to them at the right times. I am not too sure what to be searching for in terms of a tutorial on how to do this.

What I am planning on doing is: when a user comes to my site, they will set their timezone by selecting it from a dropdown list. I will store their settings in my database and use it to calculate the times.

I am not sure what I need. What should be my database time be storing? I read somewhere that it should be stored as UTC. How do I set up my database to do this? Also, I will be on a shared hosting site so it has to be set in a way that I can do it (maybe through webconfig?).

Next, I would need a list of all the timezones as either an HTML helper or regular HTML. I really don't want to make one.

Then, like I said, I need a tutorial showing me what to do. I think it is adding and subtracting stuff from that time, but I could be wrong.

question from:https://stackoverflow.com/questions/1320048/how-to-do-timezones-in-asp-net-mvc

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

For this purpose, you should definitely be storing your timestamps in UTC in the database.

When you need to display a date from the database on your site, you can do this:

DateTime stamp = /* get datetime from the database here, make sure you
                    use the constructor that allows you to specify the 
                    DateTimeKind as UTC. */

//E.g.
//DateTime stamp = new DateTime(2009, 12, 12, 12, 12, 12, DateTimeKind.Utc);

timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById(" /* users time zone here */"); 
var convertedTime = TimeZoneInfo.ConvertTime(stamp, timeZoneInfo);

//Print out the date and time
//Console.WriteLine(convertedTime.ToString("yyyy-MM-dd HH-mm-ss")); 

The list of timezones is already available in .Net, so you can see this post on how to enumerate them. For ASP.Net MVC, instead of printing the time out, you would want to assign the converted datetime to a property of your model class so your View could use it for display.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...