Ajax Calender With Timezone

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
 

  1. <script type="text/javascript">  
  2.    function clientShowing(sender, args) {  
  3.    sender.set_todaysDate(new Date('<%= ToCalenderFormat(GetDatetimewithtimezone("Pacific Standard Time"),GetTimeSpanDifference("Pacific Standard Time")) %>'));  
  4.    sender.set_startDate('<%= ToCalenderFormat(GetDatetimewithtimezone("Pacific Standard Time"),GetTimeSpanDifference("Pacific Standard Time")) %>');  
  5.    sender.set_endDate('<%= ToCalenderFormat(GetDatetimewithtimezone("Pacific Standard Time").AddDays(7),GetTimeSpanDifference("Pacific Standard Time")) %>');  
  6.    }  
  7. </script>   
C# 
  1. //Format Datetime with respect to CalendarExtender  
  2. public static String ToCalenderFormat(DateTime dt, TimeSpan TimeZoneDifference)  
  3. {  
  4.    return new DateTimeOffset(dt.Ticks, TimeZoneDifference).ToString("yyyy-MM-ddTHH:mm:ssZ");  
  5. }  
  6. //Get Datetime of Specific TimeZone  
  7. public static DateTime GetDatetimewithtimezone(string Timezone)  
  8. {  
  9.    return (TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, TimeZoneInfo.FindSystemTimeZoneById(Timezone)));  
  10. }  
  11. //Get Time Difference between Specific Timezone and UTC  
  12. public static TimeSpan GetTimeSpanDifference(string Timezone)  
  13. {  
  14.    TimeZoneInfo TZI = TimeZoneInfo.FindSystemTimeZoneById(Timezone);  
  15.    return TZI.BaseUtcOffset;  
  16. }  
HTML
  1. <asp:ScriptManager ID="ScriptManager1" runat="server" />  
  2. <asp:TextBox ID="txtDate" runat="server" CssClass="disable_future_dates" />  
  3. <asp:ImageButton runat="server" ID="imgPopup" ImageUrl="~/Calendar.png" />  
  4. <AjaxControlToolkit:CalendarExtender ID="CalendarExtender1" runat="server" TargetControlID="txtDate" PopupButtonID="imgPopup" OnClientShowing="clientShowing" />  
Output

Clalendar

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. 


Similar Articles