Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to get user local time at Page_Load
    text
    copied!<p>I have a web page written in ASP.NET and I need to retrieve the end user's local time at <code>Page_Load</code>. I thought about using Javascript to get the local time (by using <code>new Date()</code>) but the problem is that the script is run after the server events. </p> <p>Any ideas on how to accomplish this?</p> <p>EDIT: My page is quite complex: it displays a chart with lots of calculated fields from a database, object/fields selection lists, etc; The customer now requested that it should consider the user's timezone and that the timezone should be determined automatically by the web page. The user date is important to determine the chart interval (which day to display data on). Data loading (since it is so complicated) is done in both <code>Page_Load</code> and <code>Page_PreRender</code>. Giving up these events would require a full page rewrite.</p> <p>FINAL SOLUTION INSPIRED BY ANSWER: Here is how I solved the problem eventually. I am keeping the local date in a cookie. Here is the method that sets the cookie:</p> <pre><code>function SetLocalDateCookie() { var cookieName = 'LOCALDATE'; var localDate = new Date(); var realMonth = localDate.getMonth() + 1; var localDateString = localDate.getFullYear() + "/" + realMonth + "/" + localDate.getDate(); setCookie(cookieName, localDateString, 2); try { var exdate = new Date(); exdate.setDate(exdate.getDate() + 2); document.cookie = cookieName + "=" + escape(localDateString) + ";expires=" + exdate.toGMTString(); } catch (e) { } } </code></pre> <p>In my Master page I call this method on <code>$(document).ready</code>. On the page where I use this cookie I added the following code to <code>Page_Init</code>:</p> <pre><code>if (string.IsNullOrEmpty(CookieHandler.Instance.GetCookie(CookieKeys.LocalDate))) { Response.ClearContent(); Response.Write(@"&lt;form id='local' method='post' name='local'&gt; &lt;script type='text/javascript'&gt; SetLocalDateCookie(); document.getElementById('local').submit(); &lt;/script&gt; &lt;/form&gt;"); Response.Flush(); Response.End(); } </code></pre> <p>Then I can just use the cookie value in the C# code. Thank you for your answers/comments!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload