• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 799
  • Last Modified:

How to set Cookie.Expire time?

Hoi all...
I have trouble with the following code:
                  DateTime dtNow = DateTime.Now;
                  TimeSpan tsMinute = new TimeSpan(365, 0, 0, 0);
                  HttpCookie myCookie = new HttpCookie(cookieName);
                  myCookie.Expires = dtNow + tsMinute;
                  myCookie["memberID"] = iMemberID.ToString();
                  myCookie["memberNick"] = sMemberNick;
                  myCookie["memberPassword"] = sMemberPassword;
Now I check, what the expire time for the cookie is:
                  myCookie = inPage.Request.Cookies[cookieName];
                  Response.Write("this cookie expires: "+myCookie.Expires);
I always get:
01.01.0001 00:00:00

The idea how to set the cookie is taken from here:

Can someone tell me how I tell my cookie to life for 365 days from now?

Thank you.
2 Solutions
SmoerbleAuthor Commented:
This contains
DateTime dtExpiry = DateTime.Now.AddDays(iDaysToExpire);
Response.Cookies[cookiename].Expires =dtExpiry;
I did that too, same result as above: expire time seems not to be correct.
Any other idea?
SmoerbleAuthor Commented:
I checked what the browser says about the cookie:
the date is set correctly... so the question is, why doesn't it display the correct date in my code?
Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

Hmmm... I am wondering if you are cheking your cookie after another page hit?  If you are checking your cookie after setting it you are looking at the wrong object.  You set your cookie on Response and check on Request.  Also, if cookies are turned off on the browser then this may happen.
SmoerbleAuthor Commented:
Ok, as stated in
the cookie does not send back the correct dateTime when using ....Expires.
Thank you.

If anybody has any other idea, please feel free to share ;)
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

7 new features that'll make your work life better

It’s our mission to create a product that solves the huge challenges you face at work every day. In case you missed it, here are 7 delightful things we've added recently to monday to make it even more awesome.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now