Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to store DateTime into cookies?

I am working on an ASP .NET project, and currently I am using this code to store and retrieve DateTime on cookies:

HttpCookie cookie = new HttpCookie("myCookie");
if (Request.Cookies["myCookie"] != null)
{
    cookie = Request.Cookies["myCookie"];
}
else
{
    cookie["From"] = DateTime.Now.AddDays(-7).ToShortDateString();
    cookie["To"] = DateTime.Now.ToShortDateString();
    Response.Cookies.Add(cookie);
}
model.FromDate = DateTime.Parse(cookie["From"]);
model.ToDate = DateTime.Parse(cookie["To"]);

And in my View I am using Razor to recovery the model values like this:

<input type="text" id="from" value="@Model.FromDate.ToShortDateString()" readonly="readonly" />
<input type="text" id="to" value="@Model.ToDate.ToShortDateString()" readonly="readonly" />

It is working fine when I run it locally, but when I uploaded to production, when recovering the DateTime from cookie, the date is changed in one day. For example, I selected a date range from 3/25/2016 to 4/1/2016, then I have gone to another page, and when I came back to this page, the page showed a date range from 3/24/2016 to 3/31/2016, decreased in one day.

Do you know what I am doing wrong here, why this just happens in production (I suppose is something related to server date) and, finally, what is the best way to store and retrieve a DateTime on cookie?

like image 870
Marcello Avatar asked Dec 24 '22 07:12

Marcello


1 Answers

You can store the date in Ticks

cookie["From"] = DateTime.Now.AddDays(-7).Ticks.ToString();
cookie["To"] = DateTime.Now.Ticks.ToString();

and recover like this:

model.FromDate = new DateTime(Convert.ToInt64(cookie["From"]));
model.ToDate = new DateTime(Convert.ToInt64(cookie["To"]));

Hope this helps you

like image 123
Samuel R Ferreira Avatar answered Dec 29 '22 05:12

Samuel R Ferreira