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?
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
When storing date / time as string
you should always consider timezones. I recommend you to use DateTimeOffset
instead of DateTime
:
var now = DateTimeOffset.Now;
var asString = now.ToString(CultureInfo.InvariantCulture);
var asDatetimeOffset = DateTimeOffset.Parse(asString, CultureInfo.InvariantCulture);
The string looks like this: 04/01/2016 22:01:09 +02:00
(You need to know the client's timezone to correctly calculate its 'local' time. In your example, the server uses it's own time.)
The result of DateTime.Parse(cookie["From"]);
is set to DateTimeKind.Unspecified
. Any further operation (like AddDays) depends the system's timezone.
I think you should specify the culture and tell the parser which DateTimeKind
to expect:
model.FromDate = DateTime.Parse(cookie["From"], CultureInfo.CurrentCulture, DateTimeStyles.AssumeLocal);
model.ToDate = DateTime.Parse(cookie["To"], CultureInfo.CurrentCulture, DateTimeStyles.AssumeLocal);
Note : DateTime.ToShortDateString isn't a good choice, since it is defined by the current culture's DateTimeFormatInfo object.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.