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

How do I set cookie expiration time in user local time?

1个答案

1

When setting cookie expiration time, considering the user's local time is crucial as it directly impacts user experience and effective cookie management. Typically, cookie expiration time is defined by setting the Expires attribute or the Max-Age attribute. Since standard time formats in HTTP headers and JavaScript for setting cookies use GMT (Greenwich Mean Time) or UTC (Coordinated Universal Time), we need to convert the user's local time to GMT or UTC for setting.

1. Getting the User's Local Time Offset

First, we need to calculate the offset between the user's local time and UTC time. In JavaScript, we can use the Date object's getTimezoneOffset() method to obtain this offset. This method returns the difference in minutes between local time and UTC time.

For example, if the user is in Tokyo (UTC+9), getTimezoneOffset() returns -540 (as Tokyo is 9 hours ahead of UTC, resulting in a negative value).

2. Converting Time

Suppose we want to set the cookie to expire at 8 PM local time for the user. We can first create a Date object set to 8 PM of the current day for the user, then adjust this time to UTC based on the offset.

javascript
let localExpireHour = 20; // User's local time at 8 PM let now = new Date(); now.setHours(localExpireHour, 0, 0, 0); // Set to 8 PM today // Get the offset and convert to milliseconds let offset = now.getTimezoneOffset() * 60 * 1000; // Convert to UTC time let utcExpireTime = new Date(now.getTime() - offset); // Set cookie document.cookie = `username=John Doe; expires=${utcExpireTime.toUTCString()}; path=/`;

3. Using Max-Age Instead of Expires

Another approach is to use the Max-Age attribute, which defines the number of seconds the cookie remains valid from its creation. This method does not require time conversion; it only requires knowing how many seconds from now the user's local time will reach 8 PM.

javascript
let localExpireHour = 20; // User's local time at 8 PM let now = new Date(); now.setHours(localExpireHour, 0, 0, 0); let maxAge = (now.getTime() - Date.now()) / 1000; // Convert to seconds document.cookie = `username=John Doe; max-age=${maxAge}; path=/`;

Both methods can set cookie expiration time based on the user's local time. The choice between them depends on specific requirements and preferences. Using Max-Age is simpler and more direct, while Expires may be better supported in some older browsers.

2024年8月12日 14:18 回复

你的答案