How to get user local time at Page

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!


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

I don't think this would be possible, you can't get the time off the client's local machine at server side.

The only way to achieve this would be using some javascript (as this is client based, so it will use the client's current date/time). But as you've stated, this will be after your server events have been ran, and your web page has been rendered into HTML and sent to the client.

One alternative would be to capture the clients time before the Post Back, but it wouldn't be possible to do this with an inital Page_Load .


如何在页面上放置一个隐藏文本框,在C#中使用OnChange-eventhandler附加它,并使用OnLoad JavaScript函数将该值设置为您需要的来自客户端的值?

链接地址: http://www.djcxy.com/p/58564.html

上一篇: Haskell中的代理或函数式语言?

下一篇: 如何在页面获取用户本地时间