1

On my ASP.NET website I have a lot of pages with timestamps. I want to convert timestamps on-fly from the server time to the browser time. For that purpose I need to get client's timezone offset in code-behind.

What I tried is to set TimezoneOffset cookie in the <head> of every page using JavaScript. But it (obviously) not works when page is loaded in first time (and no cookie was set before).

Is there any elegant solution to convert dates from server to client time?

The only solution I see is to check TimezoneOffset cookie in Page_Load, then redirect to dummy page that will set this cookie, and then using JS redirect back to original page, but I do not like this solution.

Denis
  • 3,653
  • 4
  • 30
  • 43

2 Answers2

0

I don't think you can access any user's information before they go to a page, but you could in the head, check for the cookie and reload the page. This would look something like this:

var time = getCookie("timezoneoffset");
if(time !== undefined) {
    //congrats, the timezone is set!
} else {
    //set the cookie here, then do this:   
    location.reload()
}
Travis
  • 1,274
  • 1
  • 16
  • 33
  • I used described method, but it has a problem: I use `UpdatePanel`s, and they are displayed BEFORE scripts run, so users see dates flickering. I am trying somehow to redesign this (convert dates on server-side). – Denis Jan 29 '15 at 23:49
0

You can use Wyatt's solution by doing a refresh after you set the cookie (of course you'll have to ignore the real 1st request since it has no cookie)

var time = getCookie("timezoneoffset");
if(time != undefined) {
    //congrats, the timezone is set!
} else {
    //set the cookie here, then do this ....
    location.reload();
}

Did you consider doing this transformation client side? It may be a better solution (but depends a lot on your app architecture).

Also this way you limit your potential clients to those who accept cookie (but that is another story).

Travis
  • 1,274
  • 1
  • 16
  • 33
Adrian P.
  • 31
  • 1
  • 6
  • I transform it client-side now, but I have the problem: I use `UpdatePanel`, so I have to register "replaceDates" script in `ScriptManager.RegisterStartupScript` but scripts registered with `RegisterStartupScript` are executed 1-2 seconds AFTER page is displayed, and I see how my dates are changed from UTC to local time. – Denis Jan 30 '15 at 00:07
  • If you are ok with loosing the first request you can setup the cookie client side and refresh the page after. – Adrian P. Jan 30 '15 at 00:28
  • See also http://stackoverflow.com/questions/338482/can-you-determine-timezone-from-request-variables but the principle for the simple way of doing this (2) is the same. The hard way (1) is by using geo location based on IP which involves a lot of fun, I think ... – Adrian P. Jan 30 '15 at 00:38
  • That makes more sense than using `innerHTML` in this case, can't believe I didn't think of it. –  Jan 31 '15 at 02:55