Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get user local time at Page_Load

I have a web page written in ASP.NET and I need to retrieve the end user's local time at Page_Load. I thought about using Javascript to get the local time (by using new Date()) but the problem is that the script is run after the server events.

Any ideas on how to accomplish this?

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 Page_Load and Page_PreRender. Giving up these events would require a full page rewrite.

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:

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)
    { }
}

In my Master page I call this method on $(document).ready. On the page where I use this cookie I added the following code to Page_Init:

if (string.IsNullOrEmpty(CookieHandler.Instance.GetCookie(CookieKeys.LocalDate)))
{
    Response.ClearContent();
    Response.Write(@"<form id='local' method='post' name='local'>
                        <script type='text/javascript'>
                            SetLocalDateCookie();
                            document.getElementById('local').submit();
                        </script>
                    </form>");
    Response.Flush();
    Response.End();
}

Then I can just use the cookie value in the C# code. Thank you for your answers/comments!

like image 776
Ioana Marcu Avatar asked Mar 27 '12 11:03

Ioana Marcu


1 Answers

I'll explain a bit the following code and what lefts for you to do.

At the first request off this page, the code checks if the LocalTime is not already stored in Session and if not it will write a form element, a hidden input and a javascript which will post that form with the local time. The response ends, so your report won't get the chance to be generated.

This submit will immediately create a POST request with the localTime set, then ASP .Net stores this POST value into the Session.

I also added a 302 redirect (Response.Redirect) to the original page, because of the usability. The User made initially a GET request, not a POST, so if he/she wants to refresh the page, the browser will reiterate the last action, which was that form.submit() and not the GET request.

You have now the local time. But you don't have to read it at every request since it can be compared to the UTC time, then with the server's time.

edit: You need to parse the UTC time into a DateTime, but probably it's easy to find the format, though might depend on the user's culture (not sure about this statement).

public ReportPage()
{
    this.Init += (o, e) =>
    {
        // if the local time is not saved yet in Session and the request has not posted the localTime
        if (Session["localTime"] == null && String.IsNullOrEmpty(Request.Params["localTime"]))
        {
            // then clear the content and write some html, a javascript code which submits the local time
            Response.ClearContent();
            Response.Write(@"<form id='local' method='post' name='local'>
                                <input type='hidden' id='localTime' name='localTime' />
                                <script type='text/javascript'>
                                    document.getElementById('localTime').value = new Date();
                                    document.getElementById('local').submit();
                                </script>
                            </form>");
            // 
            Response.Flush();

            // end the response so PageLoad, PagePreRender etc won't be executed
            Response.End();
        }
        else
        {
            // if the request contains the localtime, then save it in Session
            if (Request.Params["localTime"] != null)
            {
                Session["localTime"] = Request.Params["localTime"];
                // and redirect back to the original url
                Response.Redirect(Request.RawUrl);
            }
        }
    };
}
like image 183
Adrian Iftode Avatar answered Oct 03 '22 22:10

Adrian Iftode