How to expire a cookie in 30 minutes using jQuery? - javascript

How to Expire a Cookie in 30 min ? I am using a jQuery cookie.
I am able to do something like this.
$.cookie("example", "foo", { expires: 1 });
This is for 1 day. But how can we set expiry time to 30 min.

30 minutes is 30 * 60 * 1000 miliseconds. Add that to the current date to specify an expiration date 30 minutes in the future.
var date = new Date();
var minutes = 30;
date.setTime(date.getTime() + (minutes * 60 * 1000));
$.cookie("example", "foo", { expires: date });

If you're using jQuery Cookie (https://plugins.jquery.com/cookie/), you can use decimal point or fractions.
As one day is 1, one minute would be 1 / 1440 (there's 1440 minutes in a day).
So 30 minutes is 30 / 1440 = 0.02083333.
Final code:
$.cookie("example", "foo", { expires: 30 / 1440, path: '/' });
I've added path: '/' so that you don't forget that the cookie is set on the current path. If you're on /my-directory/ the cookie is only set for this very directory.

I had issues getting the above code to work within cookie.js. The following code managed to create the correct timestamp for the cookie expiration in my instance.
var inFifteenMinutes = new Date(new Date().getTime() + 15 * 60 * 1000);
This was from the FAQs for Cookie.js

Related

Why won't my timer reset every three days dynamically?

I'd like to know what I'm doing wrong in the logic of my code where I'm trying to make the timer reset every three days. In the code below, I have the timer set to expire September 1, 2019, which's three days from now.
I want it to reset on its own to September 4, 2019, then September 7, 2019, etc.
What am I doing wrong & how can I rectify this? A JSFiddle's also provided below.
https://jsfiddle.net/des6gjqa/
<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
p {
text-align: center;
font-size: 60px;
margin-top: 0;
}
</style>
</head>
<body>
<p id="demo"></p>
<script>
// Set the date we're counting down to
var countDownDate = new Date("Sep 1, 2019 9:45:00").getTime();
while(countDownDate.valueOf() < Date.now()) {
countDownDate = new Date(countDownDate.valueOf() + (3 * 24 * 60 * 1000)); // add 3 days to the start date
}
// Update the count down every 1 second
var x = setInterval(function() {
// Get today's date and time
var now = new Date().getTime();
// Find the distance between now and the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Output the result in an element with id="demo"
document.getElementById("demo").innerHTML = days + "d " + hours + "h "
+ minutes + "m " + seconds + "s ";
// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
if(countDownDate.valueOf() <= Date.now()) {
countDownDate = new Date(countDownDate.valueOf() + (3 * 24 * 60 * 1000));
}
}, 1000);
</script>
</body>
</html>
Your issue is less complex than what you are thinking. Consider the following:
JavaScript is a client side language (for this example)
The browser data (localStorage, cache, etc) can be easily manipulated.
JavaScript execution stops when the page is closed.
So, the only way to reset the timer every three days with what you are trying is to not close the window during three days. Because when you close it and visit the site once again, the timer will start from 0.
What should you do?
The best approach to this is to have something running on a server. (i.E. PHP, Node.js, Python, Java, etc)
And then, you should use a method to identify the user's machine like the IP address, a custom token (generated server side), etc.
This way, you could assign a cookie to the user visiting your site with a session ID and save in a database the starting date. By doing this, you can easily compare anytime the actual date with the start date anytime and then eval if the lapse is bigger than 3 days, show EXPIRED.
Because otherwise, the script you provided will start counting 3 days every time it is loaded.
See k3llydev's answer for a more robust fix. If you wish for this code to be client side with the assumption that the webpage will be open for the entire duration, here I have made modifications to your jsfiddle: https://jsfiddle.net/as57fjuL/.
Essentially, it is just resetting the 'x' interval after clearing the interval and setting the date again. For simplicity, I have manually set the timeout to about 3 seconds (which can be changed by removing the line countDownDate = new Date(Date.now().valueOf() + 5000);).
You miss second in your expression:
instead of (3 * 24 * 60 * 1000) you should use (3 * 24 * 60 * 60 * 1000)

Javascript countdown and Timezones

enter image description here
basically I insert a row with a datetime + interval (something in the future) with a SQL query.
$interval = new DateInterval('PT'.$H.'H'.$i.'M'.$s.'S');
$date = new DateTime(); $date->add($interval);
$query = $conn->prepare("INSERT INTO profiles_in_missions (id_pim, id_profile, id_mission, time) VALUES (NULL, :idprofile, :idmission,:time)");
$query->bindValue(':idprofile', $tableau[0]);
$query->bindValue(':idmission', $id);
$query->bindValue(':time', $date->format('Y-m-d H:i:s'));
$query->execute();
If my pc shows: 23:40, and if i insert DateTime with interval of +8minutes, this query will store 21:48 in the database. Till now okay, my database is GTM+00 and my pc default browser is GTM+2.
Once stored, i am trying to pick this date who got (in that case) -2h+8m and and make a countdown.
Now the problem: To make the countdown, i am using javascript and i do 21:48-now(); BUT he will always end 2h faster than normal, because the stored date (21:48) in MYSQL with GTM+00 BUT Javascript now(); is getting my default browser time GTM+2.
Is there a way to make Javascript work with server Timezone GTM+00? How can i fix my problem? There is all my code for the countdown:
<script>
var t = document.getElementById('myInputTimer').value;
var countDownDate = new Date(t).getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now an the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Display the result in the element with id="demo"
document.getElementById("demo").innerHTML = hours + "h "
+ minutes + "m " + seconds + "s ";
// If the count down is finished, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
</script>
new Date().getTime() (which can be replaced with Date.now()) simply returns the number of milliseconds from date zero. Timezone isn't a factor here, where timezone becomes a factor is here:
var t = document.getElementById('myInputTimer').value;
var countDownDate = new Date(t).getTime();
If the string you use to create the date object doesn't contain any timezone information, it assumes the timezone of the browser.
I'm assuming this string is the date you have in UTC time?
One solution is to make sure this string contains timezone information, which means it would look like this: 2017-06-03T22:23:00+00:00
Another solution is to correct for the timezone offset after you've parsed the date. So if new Date("2017-06-03 22:23:00") gives you Sat Jun 03 2017 22:23:00 GMT+0200 (CEST) which is 20:23 you can correct it by subtracting the timezone offset:
var countDownDate = new Date(t).getTime() - (new Date().getTimezoneOffset() * 60 * 1000);
.getTimezoneOffset() returns the timezone offset in minutes, we calculate how many milliseconds it is and then subtract it from the milliseconds returned by .getTime()
Using a string to create a date isn't the best idea however since it's implementation dependent and unreliable. It's better to parse out the various components (year, month, day, hours, and so on) and construct the date with those. You can use a regexp to parse out the components like this:
var dateParts = t.match(/\d+/g);
And the best part is that now you can use Date.UTC() instead of new Date(t).getTime() to get the time in UTC directly:
var countDownDate = Date.UTC.apply(null, dateParts);

Javascript date issue in firefox

I have created a date object for Jan 1 1970 and increasing 60 minutes through iteration.
d = new Date(1970, 0, 1);
loop Start
d.setTime(d.getTime() + (60 * 60 * 1000) );
loop End
while date object reaches 10 AM and adding 60 minutes to that also return the same time(10 AM).
This problem occurred only with fire fox browser.
that too only my machine timezone is Australia/Melbourne.

Convert milliseconds to time in extjs or javascript

Is there a built in method in extjs or javascript for converting milliseconds to a time?
I found one for date, but it doesn't work. I always get Jan, 1 1970 08:00 (Pacific Standard Time). When I try test.getHours I get 0. I am trying to print out 8:00 or 08:00
var getSignOnRecord = 28800000;
var test = new Date(getSignOnRecord);
test.getHours() // 0 ???? Should be 8
you can use ISOString date formats for up to 24 hours of time:
new Date(28800000).toISOString().split("T")[1].split(".")[0]; // == "08:00:00"
you can easily slice() the remaining text to eliminate seconds or whatnot.
this works because using a "unix" stamp results in an GMT offset, and ISO also displays GMT, so by throwing away the date part, you're left with a pretty readable format of up to 23h59m59s...
You are getting the localized hour, but you want the hours at UTC
new Date(28800000).getUTCHours() // 8
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getHours
The getHours() method returns the hour for the specified date, according to local time.
new Date(value);
value: Integer value representing the number of milliseconds since 1 January 1970 00:00:00 UTC
28800000 ms is indeed 1 January 1970, 8h
When I try test.getHours I get 0
NB value is UTC, getHours is local time
This is a math problem. As far as I know, there is no function that does this in native JavaScript, but can be coded from scratch.
function convertToTime(milliseconds) {
var seconds = Math.floor(milliseconds / 1000) % 60
var minutes = Math.floor(milliseconds / (1000 * 60)) % 60
var hours = Math.floor(milliseconds / (1000 * 60 * 60)) % 24
return (hours < 10 ? "0" + hours : hours) + ":" +
(minutes < 10 ? "0" + minutes : minutes) + ":" +
(seconds < 10 ? "0" + seconds :seconds);
}
There's also probably a method like this in momentjs.

Some explanations on Date.now

Could someone explain to me what this returning number means? and how it is derived to that?
console.log(Date.now() - 24 * 60 * 60 * 1000);
If I wanted to use the above formula to display the next 15minutes and not 24 hours? how would I alter it?
Date.now() returns:
the number of milliseconds elapsed since 1 January 1970 00:00:00 UTC.
24 * 60 * 60 * 1000 in milliseconds represents 24 hours*. So you basically get a timestamp 24 hours in the past from now. Notice that due to DST this doesn't necessarily compute a timestamp one day in the past. It's 24 hours in the past.
Also to get some meaningful output you should wrap resulting number in Date:
console.log(new Date(Date.now() - 24 * 60 * 60 * 1000));
Finally Date.now() can be replaced with new Date() when using in arithmetic expression.
* - 24 (hours) times 60 (minutes in hour) times 60 (seconds in minute) times 1000 milliseconds in second.

Categories