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

Set cookie to expire after fixed date, not x amount of time

Hi,

I'm trying to set a cookie to expire every morning at 9am.
How should i do this (with jQuery)?

Set, read, delete is all working fine.
This sets the cookie to expire after 1 day, i want it to expire next day @ 9am.
$.cookie("newsq", "1", { path: '/', expires: 1 });

is this possible?
0
peps03
Asked:
peps03
  • 4
  • 3
2 Solutions
 
Julian HansenCommented:
When you set the cookie work out how long between time you are setting the cookie and 9am - convert that to seconds and set the cookie.
0
 
peps03Author Commented:
Thanks.
I've been trying to get it to work this way, since your post.
I'm not managing.

Could you maybe help me with the code?

the cookie is set to 0 by default.
once a button is clicked, it is set to 1. until it is supposed to expire.
0
 
Julian HansenCommented:
How about this?
function setCookie(value)
{
  // Get date and time now
  var cur = new Date();

  // Add a day 86,400 secs * 1000 ms
  var tn = new Date(cur.getTime() + 86400000);
  
  // Create a new date with tomorrows Year / Month and day but 9 in the morning
  var et = new Date(tn.getFullYear(), tn.getMonth(), tn.getDate(), 9,0);

  // Finally create your cookie outputing new date as a UTCString
  document.cookie='mycookie=' + escape(value) + '; expires=' + et.toUTCString();
}

Open in new window

0
Cloud Class® Course: Microsoft Azure 2017

Azure has a changed a lot since it was originally introduce by adding new services and features. Do you know everything you need to about Azure? This course will teach you about the Azure App Service, monitoring and application insights, DevOps, and Team Services.

 
peps03Author Commented:
thanks. for testing purposes, how would i set it just minutes in the future?
0
 
Julian HansenCommented:
Something like this ...

var dt = new Date();
var min = 10; // change to whatever you want
var nd = new Date(dt.getTime() + (min * 60 * 1000));

Open in new window

0
 
peps03Author Commented:
Thanks!!! It works like a charm! :)
0
 
Julian HansenCommented:
Nice!
0
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

Cloud Class® Course: CompTIA Cloud+

The CompTIA Cloud+ Basic training course will teach you about cloud concepts and models, data storage, networking, and network infrastructure.

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