Reputation: 1494
I am trying to set a cookie which stores the current TimezoneOffset.
window.onload = function () {
var timezone_cookie = "timezoneoffset";
if (!$.cookie(timezone_cookie)) { // if the timezone cookie not exists create one.
// check if the browser supports cookie
var test_cookie = 'test cookie';
$.cookie(test_cookie, true);
if ($.cookie(test_cookie)) { // browser supports cookie
// delete the test cookie.
$.cookie(test_cookie, null);
// create a new cookie
$.cookie(timezone_cookie, new Date().getTimezoneOffset());
location.reload(); // re-load the page
}
}
else { // if the current timezone and the one stored in cookie are different then
// store the new timezone in the cookie and refresh the page.
var storedOffset = parseInt($.cookie(timezone_cookie));
var currentOffset = new Date().getTimezoneOffset();
if (storedOffset !== currentOffset) { // user may have changed the timezone
$.cookie(timezone_cookie, new Date().getTimezoneOffset());
location.reload();
}
}
};
But when I try to read the value later, the debugging Tool in Visual Studio tells me, it is "null".
If I load the page and inspect the cookies, a value (-120) is set. Can someone tell me what I am doing wrong?
The javascript is within the _Layout.cshtml file. The code I want to execute with the cookie looks like this:
var timeOffSet = HttpContext.Current.Session["timezoneoffset"]; // read the value from session
if (timeOffSet != null)
{
var offset = int.Parse(timeOffSet.ToString());
dt = dt.AddMinutes(-1 * offset);
return dt.ToString("yyyy-MM-dd HH:mm");
}
// if there is no offset in session return the datetime in server timezone
return dt.ToLocalTime().ToString("yyyy-MM-dd HH:mm");
Function is called from a View, so the js code should have been executed by this time.
Upvotes: 0
Views: 416
Reputation: 26
I think that you try to get the value in a wrong way - the cookies are not stored in session variable.
You can use this line instead:
HttpCookie cookie = Request.Cookies["timezoneoffset"];
if ((cookie != null) && (cookie.Value != ""))
{
var offset = int.Parse(cookie.Value.ToString());
dt = dt.AddMinutes(-1 * offset);
return dt.ToString("yyyy-MM-dd HH:mm");
}
return dt.ToLocalTime().ToString("yyyy-MM-dd HH:mm");
Upvotes: 1