Monday, June 11, 2012

DateTime Format With Time Zones

The problem:

In my Visual Web Part, I have to display a current date in the following format:

1:29 pm EDT June 11, 2012

The usual way to display the current date in this format is via <%=DateTime.Now.ToString("H:MM tt K MMMM d, yyyy"). The problem with this approach, though, is that the time zone is displayed in the wrong format, more like

1:29 pm -04:00 June 11, 2012

The solution:

First, we need to find the acronym current time zone. The following two functions take  care of it:


Next, we need to split the formatted date string (where the white space is the delimiter), and replace the second element (i.e., "-04:00") with the proper acronym (i.e., "EDT.") The following code takes care of it:


Finally, in the code-behind for the user control for the Web Part, create a protected method (e.g., ToProperFormat()) and make it return DateTime.Now.ToProperFormat(). Then, in the ASCX file, call <%=ToProperFormat() %> . Note that calling the extension method directly from the ASCX file results in a compilation error unless you import the extension namespace.

No comments:

Post a Comment