乐闻世界logo
搜索文章和话题

Which date formats can I use when specifying the expiry date when setting a cookie?

1个答案

1

When setting the expiration time for cookies, specific date formats are typically required to ensure browsers correctly parse and store this information. Generally, the most commonly used date formats are GMT (Greenwich Mean Time) or UTC (Coordinated Universal Time). This format is commonly referred to as HTTP-date format, defined in RFC 7231 and RFC 5322.

Specifically, the date format must adhere to the following standards:

  • Complete Date and Time: Wdy, DD Mon YYYY HH:MM:SS GMT

Each component is defined as:

  • Wdy represents the day of the week (e.g., Mon, Tue, Wed, Thu, Fri, Sat, Sun)
  • DD represents the day of the month (two-digit, e.g., 01, 15, 30)
  • Mon represents the month (e.g., Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec)
  • YYYY represents the year (e.g., 1995, 2020, 2023)
  • HH:MM:SS represents the time (hours:minutes:seconds)
  • GMT specifies the time zone as Greenwich Mean Time.

For example, to set a cookie expiring at midnight on December 25, 2023, configure the Expires attribute as follows:

http
Set-Cookie: name=value; Expires=Mon, 25 Dec 2023 00:00:00 GMT

This format ensures browsers correctly parse the expiration time. In development practice, various programming languages provide date-time functions to generate compliant date strings. For instance, in JavaScript, the toUTCString() method produces a GMT-formatted string meeting these specifications:

javascript
const date = new Date('December 25, 2023 00:00:00'); const cookieValue = `name=value; Expires=${date.toUTCString()}`;

This guarantees the cookie has a correctly formatted expiration date, expiring after the specified time.

2024年8月12日 11:31 回复

你的答案