Search code examples
angularcookiesangular2-cookie

How to add expiry time in hours for a cookie in Angular 2?


How to add expiry time in hours for a cookie, I am able to do with days.

Cookie.set('SESSION_TOKEN', sessionToken, 6); // here 6 is days

I want in hours. I want cookie to be expired in 6 hours.

Cookie.set('SESSION_TOKEN', sessionToken, 6(hours)); // 6 hours

Below is the code I am using, but I am getting an error "Argument of type 'Date' is not assignable to parameter of type 'number'"

setCookie(userObject) {
    let expire = new Date();
    var time = Date.now() + ((3600 * 1000) * 6);
    expire.setTime(time);
    console.log("expire "+expire);
    Cookie.set('USER_NAME',Base64.encode(userObject.user.email),expire);
    Cookie.set('SESSION_TOKEN',userObject.sessionToken,expire);
}

Solution

  • I had done like this, it worked for me.

     Cookie.set('SESSION_TOKEN',userObject.sessionToken,0.25);
    

    Actually if we give 1 it stays long for 24hrs, So I applied mathematical logic to it, i.e. for 6 hours.

    1 day -> 24 hrs
    ? day -> 6 hrs
    (1*6)/24 -> 0.25 i.e. 6hrs