Use-by dates

By default, cookies are set to expire after the current session, so in most cases, you will want to set the expiry date to a later time. While this can be accomplished by setting a hard-coded date to the cookie property, using JavaScript's Date object simplifies the process greatly.

The Date object was first introduced in the Christmas tracker example, so for a quick refresher, use the Navigator button at the top of the screen to move back to the operators example. Recall that Date objects are created using the syntax:

var myDate = new Date();

JavaScript's date object also includes numerous methods for working with date objects, some of which were introduced in the September examples. A new method that will be useful with cookies is the toGMTString() method. The toGMTString() method converts a time from the local time zone to Greenwich Mean Time (GMT). The GMT time zone is used as a standard time zone with cookies so that the cookie will expire at the same time, regardless of the user's location.

Depending on the amount of time for which you want your cookie to remain valid, you can use the Date object's setMonth() or setYear() method in combination with the getMonth() or getYear() method to set the time for the cookie to expire. This new time can then be appended to the cookie string, with a semicolon separating the cookie and expiry date. For example, if you wanted to set the cookie to expire in one year's time, you could use the following code:

var expires = new Date();

expires.setYear(expires.getYear() + 1);
document.cookie = "cookieName=cookieValue; expires=" + expires.toGMTString();