2016-02-10

ASP.NET MVC - List of System Time Zones in ViewBag (C#)

You probably don't need this if you are developing applications that are running inside one timezone (local apps, internal enterprise apps). As soon as your application gets little more ambiguous you would probably need to think about time that differs from your local server time in different parts of the world.


One approach to get beyond this is to enable user to select their time zone from the list of available time zones that are a part of Windows operating system. I will show you how to get the list and display it in MVC View.
The code bellow retrieves time zones and stores them in array of SelectListItems.

Controller:
SelectListItem[] TimezoneList;

var tzs = TimeZoneInfo.GetSystemTimeZones();
TimezoneList = tzs.Select(tz => new SelectListItem()
   {
      Text = tz.DisplayName,
      Value = tz.Id
   }).ToArray();
ViewBag.TimeZones = TimezoneList;

On view side you need to display list of time zones. As most of the sites use simple DropDownList the bellow code shows how to do this using Razor syntax.

View:
 <div class="form-group">
     @Html.LabelFor(model => model.TimeZone, htmlAttributes: new { @class = "control-label col-md-2" })
     <div class="col-md-10">
          @Html.DropDownListFor(model => model.TimeZone, new SelectList(ViewBag.TimeZones, "Value", "Text"), new { @class = "form-control" })
          @Html.ValidationMessageFor(model => model.TimeZone, "", new { @class = "text-danger" })
     </div>
</div>
What is your preferred way of handling time and time zones in your code?

No comments:

Post a Comment