PDA

View Full Version : Set cookie question & time



Nomadicus
Dec 5th, 2002, 12:06 AM
I'm trying to set a cookie to expire one hour in the future (for testing purposes).

Can anyone give me some clear code, in one or two lines, how to do this?

I just want to know, in plain English, how to get the current time, and then add 60 minutes to it (and then do the funky GMT time conversion that JS needs).

The on-line manuals don't tell you anything this basic. They all want to tell you how to set cookies for the future, by converting furlongs per fortnight, adding in +4.7 parsecs Star Trek time, and then putting this thru their favorite fudge-altor function to approximate time on Alpha Centauri.

I just want to know how to set a freaking cookie for one hour in the future. In PHP this is a snap, just use time() + 3600;

But I must do this in JS.

Thanks in advance.

whammy
Dec 5th, 2002, 12:44 AM
Thanks to Dave Clark:

// for the addtime var- for one month (31 days) of milliseconds:
// 31 * 24 * 60 * 60 * 1000 = 2678400000
addtime = 60 * 60 * 1000 // 1 hour
expdate = new Date()
expdate.setTime(expdate.getTime() + addtime)
expdate = expdate.toGMTString()
document.cookie="WhateverValueYouWant" + "; expires=" + expdate;

Hope this helps. :)

Nomadicus
Dec 5th, 2002, 09:43 AM
That looks very straightforward.

= = =

I was warned not to just use "direct values" like 10000 to approximate 10 seconds when sending a cookie. And I think I discovered why.

This direct value seems to work just fine for NS 7.0 and IE 5.5 (the two browsers that I test against). But someone who is using NS 4.7 called me and complained that my application (which is still being tested) was not working. The app depends upon cookies for their default selections. They kept complaining that they could not set any defaults!

This had me stumped until I remembered someone here telling me that (thanks, whoever it was) you should not do this with cookies. The proper way is to get the current time, add whatever your future expiration time should be, convert it to GMT, and use that value.

So that is what I will do. And if it fixes the problem, I will have to conclude that earlier versions of NS will not accept a direct value like this for a cookie, but later versions will. I guess it's all in the "implementation" of things.

whammy
Dec 6th, 2002, 12:41 AM
Originally posted by Nomadicus
The proper way is to get the current time, add whatever your future expiration time should be, convert it to GMT, and use that value.

That's what the script I posted does. :)