Introduction
In this article, I will explain how to use AjaxControlToolkit CalendarExtender with specific TimeZone and to override local Timezone.
CalendarExtender Behaviour
Whenever we try to set SelectedDate,StartDate and EndDate properties of ajax calender extension from c#. The datetime will be considered as UTC and while displaying in browser always this time will be converted to local Timezone, so this will be hard to predict that our website will be always opened in specific Timezone.
To overcome this we need to set calender extender DateTime with required TimeZone using JavaScript.
Code
JavaScript
- <script type="text/javascript">
- function clientShowing(sender, args) {
- sender.set_todaysDate(new Date('<%= ToCalenderFormat(GetDatetimewithtimezone("Pacific Standard Time"),GetTimeSpanDifference("Pacific Standard Time")) %>'));
- sender.set_startDate('<%= ToCalenderFormat(GetDatetimewithtimezone("Pacific Standard Time"),GetTimeSpanDifference("Pacific Standard Time")) %>');
- sender.set_endDate('<%= ToCalenderFormat(GetDatetimewithtimezone("Pacific Standard Time").AddDays(7),GetTimeSpanDifference("Pacific Standard Time")) %>');
- }
- </script>
C#
-
- public static String ToCalenderFormat(DateTime dt, TimeSpan TimeZoneDifference)
- {
- return new DateTimeOffset(dt.Ticks, TimeZoneDifference).ToString("yyyy-MM-ddTHH:mm:ssZ");
- }
-
- public static DateTime GetDatetimewithtimezone(string Timezone)
- {
- return (TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, TimeZoneInfo.FindSystemTimeZoneById(Timezone)));
- }
-
- public static TimeSpan GetTimeSpanDifference(string Timezone)
- {
- TimeZoneInfo TZI = TimeZoneInfo.FindSystemTimeZoneById(Timezone);
- return TZI.BaseUtcOffset;
- }
HTML
- <asp:ScriptManager ID="ScriptManager1" runat="server" />
- <asp:TextBox ID="txtDate" runat="server" CssClass="disable_future_dates" />
- <asp:ImageButton runat="server" ID="imgPopup" ImageUrl="~/Calendar.png" />
- <AjaxControlToolkit:CalendarExtender ID="CalendarExtender1" runat="server" TargetControlID="txtDate" PopupButtonID="imgPopup" OnClientShowing="clientShowing" />
Output
Tech Blog
Reference.
Summary
We learned how to use AjaxControlToolkit CalendarExtender for specific Timezone using JavaScript, ASP.NET and C#. I hope this article is useful for all .NET beginners.