每个月的第一天删除cookie

时间:2017-03-22 11:04:42

标签: jquery html js-cookie

是否可以在每个月的第一天删除cookie,而不是等待cookie手动过期?这样我每个月都可以向用户显示一条消息,无论他们查看网站的次数是多少。我正在使用js-cookie。

1 个答案:

答案 0 :(得分:1)

以下代码将当前年份和月份设置为Cookie值,例如2017年3月的2017年3月。在随后的访问中,它会根据当前日期检查cookie值,如果当前日期更高,则删除先前的cookie并创建一个具有当前日期的新cookie。因此,4月1日,strDate将是20174,高于20173,因此删除之前的cookie并将其设置为新日期。

$(document).ready(function() {
     var d = new Date();
     var strYear = d.getFullYear() // cur year 
     var strMonth = d.getMonth()+1 // cur month
     var strDate = ("" + strYear + strMonth) // year + month e.g. 20173

     if (Cookies.get('cookieName') == null) { // cookie doesn't exist
        Cookies.set('cookieName', strDate, { expires: 40 }) // create cookie
        $('#modal').modal('show'); // show modal
     }
     else if (Cookies.get('cookieName') < strDate) { // cookie is older than 1 month
          Cookies.remove('cookieName'); // remove cookie to reset it
          Cookies.set('cookieName', strDate, { expires: 40 }) // create cookie
          $('#modal').modal('show'); // show modal
     }
     else {

     }
  });