Skip to content

Instantly share code, notes, and snippets.

@interactiveRob
Last active January 29, 2021 17:47
Show Gist options
  • Select an option

  • Save interactiveRob/f55a6f494726d2665eaabc3b1f0b3c6b to your computer and use it in GitHub Desktop.

Select an option

Save interactiveRob/f55a6f494726d2665eaabc3b1f0b3c6b to your computer and use it in GitHub Desktop.
Simple ES6 javascript class to set a cookie that expires after [x] number of days
export default class DismissCookie {
constructor() {
this.cookieName = 'ceg-banner-ad-dismissed';
this.cookie = {
url: this.getDomain(),
expirationDate: this.getExpiration(14),
name: this.cookieName,
value: true,
};
}
getDomain() {
return window.location.host;
}
getExpiration(numDays) {
// Get a date object for the current time
let d = new Date();
// Set it to the desired amount of days in future
console.log(d.getDate() + numDays);
d.setDate(d.getDate() + numDays);
// Zero the hours
d.setHours(0, 0, 0);
// Zero the milliseconds
d.setMilliseconds(0);
// Get the time value in milliseconds and convert to seconds
return this.generateCookieDate(d);
}
setCookie() {
let cookieString = `${this.cookie.name}=${this.cookie.value};expires=${this.cookie.expirationDate};domain=${this.cookie.url};path=/;`;
console.log(cookieString);
document.cookie = cookieString;
}
/*———— -utilites- ————*/
generateCookieDate(d) {
let d2 = (n) => {
return n < 10 ? '0' + n : n;
};
let days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
let months = [
'Jan',
'Feb',
'Mar',
'Apr',
'May',
'Jun',
'Jul',
'Aug',
'Sep',
'Oct',
'Nov',
'Dec',
];
return (
'' +
days[d.getUTCDay()] +
', ' +
d2(d.getUTCDate()) +
'-' +
months[d.getUTCMonth()] +
'-' +
d.getUTCFullYear() +
' ' +
d2(d.getUTCHours()) +
':' +
d2(d.getUTCMinutes()) +
':' +
d2(d.getUTCSeconds()) +
' GMT'
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment