Set a cookie expire after 2 hours - javascript

I have this JavaScript code:
function spu_createCookie(name, value, days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else
var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
How can I make the cookie expire after 2 hours?

If you want to use the same type of function, transform the days param into hours and pass 2 to get a 2 hour expiration date.
function spu_createCookie(name, value, hours)
{
if (hours)
{
var date = new Date();
date.setTime(date.getTime()+(hours*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else
{
var expires = "";
}
document.cookie = name+"="+value+expires+"; path=/";
}

Well -most obvious thing is to make "expire" date +2 hours ? :). Here You have nice prototype for that:
Adding hours to Javascript Date object?

Try this:
function writeCookie (key, value, hours) {
var date = new Date();
// Get milliseconds at current time plus number of hours*60 minutes*60 seconds* 1000 milliseconds
date.setTime(+ date + (hours * 3600000)); //60 * 60 * 1000
window.document.cookie = key + "=" + value + "; expires=" + date.toGMTString() + "; path=/";
return value;
};
Usage:
<script>
writeCookie ("myCookie", "12345", 24);
</script>
//for 24 hours

Try jquery-cookie. Makes it very easy to work with cookies.

The following one-liner will set a cookie, name, with the value, value, and an expiration of two hours from the time of its creation. If the optional argument, days, is supplied, the cookie will expire after that many days instead.
Warning: there is no error-checking, so if mandatory parameters are omitted when called, or arguments are mistyped, the function will throw an error.
spu_createCookie = (name, value, days) => { document.cookie = `${name}=${value}; expires=${new Date(Date.now() + (days ? 86400000 * days : 7200000)).toGMTString()}; path=/` }
Relevant JavaScript syntax concepts:
Arrow Functions
An arrow function expression is a compact alternative to a traditional function expression, but is limited and can't be used in all situations.
Template Literals
Template literals are string literals allowing embedded expressions. You can use multi-line strings and string interpolation features with them.
Ternary Operators
The conditional (ternary) operator is the only JavaScript operator that takes three operands ... This operator is frequently used as a shortcut for the if statement.

This would do it.
var now = new Date();
var time = now.getTime();
time += 7200 * 1000;
now.setTime(time);
document.cookie =
name+ '=' + value +
'; expires=' + now.toGMTString() +
'; path=/';

Related

How to set expiry date in seconds for cookie in JSCookie

I'm using the JSCookie library to save and load cookies.
Now I want to save a cookie with an expiry date. This is officially supported with days like the documentation. But how can I set the expiry in seconds or minutes instead of days?
So I have the following code from the documentation but this is for example only for 7 days:
Cookies.set('name', 'value', { expires: 7, path: '' });
Are there any possibilities to achieve this?
RTFM...
var inFifteenMinutes = new Date(new Date().getTime() + 15 * 60 * 1000);
Cookies.set('foo', 'bar', {expires: inFifteenMinutes})
I've set the cookie the expire in 15 seconds.
function createCookie(name, value) {
var date = new Date();
date.setTime(date.getTime() + (15*1000));
var expires = "; expires= " + date.toGMTString();
document.cookie = name + "=" + value + expires + "; path=/";
}

Check if time difference is less than 45 mins and run function - AngularJS

This is an easy thing to do in PHP with code like this;
if (strtotime($given_time) >= time()+300) echo "You are online";
But can't find anything on SO to do exactly this in javascript.
I want to check if the difference between a given time and the current time is less than 45mins
For instance
$scope.given_time = "14:10:00"
$scope.current_time = new Date();
I'm only concerned with the time part. I need to extract time part from new Date(); and then compare.
Then this should be true
How can I achieve this with Javascript:
if ($scope.given_time - $scope.current_time < 45 minutes) {
// do something
}
Javascript uses unix timestamps in milliseconds, so it is similar to the output of strtotime (which uses seconds).
var date = new Date();
Then you'll need to do the calculation from milliseconds. (Minutes * 60 * 1000)
You can also use date.parse() to parse a string to milliseconds, just like strtotime() in PHP does to seconds.
In full:
var date = new Date();
var last = new Date('Previous Date'); // or a previous millisecond timestamp
if ( ( date - last ) > ( 45 * 60 * 1000 ) ) {
// do something
}
You could use a static date to compare just time, this is exactly what strtotime does if you exclude the date:
var last = new Date('1/1/70 14:10:00');
var date = new Date('1/1/70 14:30:00');
However, this approach will fail if you're trying to compare time that cross over day boundaries.
Try this:
function checkTime(time) {
var date = new Date();
var date1 = new Date((date.getMonth() + 1) + "/" + date.getDate() + "/" + date.getFullYear() + " " + time);
var minutes = (date1.getTime() - date.getTime()) / (60 * 1000);
if (minutes > 45 || (minutes < 0 && minutes > -1395)) {
// greater than 45 is todays time is above 45 minutes
// less than 0 means the next available time will be tomorrow and the greater than -1395 means it will be more than 45 minutes from now into tomorrow
document.write(time + ': true<br />');
} else {
document.write(time + ': false<br />');
}
}
checkTime("14:10:00");
checkTime("16:30:00");
checkTime("17:10:00");
There's a JavaScript method called getMinutes(); you can use to get only the minutes and compare.
Your code should look something like:
var received_time = "14:10:00".split(':');
var minute = '';
if(received_time.length === 3) {
minute = parseInt(received_time[1], 10);
}
$scope.given_time = minute;
var the_time = new Date();
$scope.current_time = the_time.getMinutes();
And you now can do your thing:
if ($scope.given_time - $scope.current_time < 45 minutes) {
// do something
}
Using a library like moment.js you can simply diff the two times.
var $log = $("#log");
/* Difference between just times */
$log.append("Difference between times\n");
var givenTime = moment("14:10:00", "HH:mm:ss");
var minutesPassed = moment("14:30:00", "HH:mm:ss").diff(givenTime, "minutes");
$log.append("Minutes passed: " + minutesPassed + "\n");
if (minutesPassed < 45) {
$log.append(minutesPassed + " minutes have elapsed. Event Triggered." + "\n");
}
/* Better: Difference between times that have dates attached to them and cross a day boundary. */
$log.append("\n\nDifference between dates with times\n");
givenTime = moment("2015-12-03 23:33:00");
minutesPassed = moment("2015-12-04 00:14:00").diff(givenTime, "minutes");
$log.append("Minutes passed: " + minutesPassed + "\n");
if (minutesPassed < 45) {
$log.append(minutesPassed + " minutes have elapsed. Event Triggered." + "\n");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://momentjs.com/downloads/moment.js"></script>
<p>Results:</p>
<hr>
<pre id="log"></pre>
<hr>
Caveat: If the given time is yesterday such as 11:30pm and the current time is 12:10am then you will get the wrong result. You'd want to use a date with the time if this type of thing is an issue for your use case.
The moment.js documentation
http://momentjs.com/docs/
Angular directive for moment documentation
https://github.com/urish/angular-moment/blob/master/README.md

How to set multiple values with two differents expires dates

I'm trying to set cookie in javascript with two values.
Each of theses have a different expiration date.
For example :
var now = new Date();
now.setDate( now.getDate() + 2 );
document.cookie = "bar=foo;";
document.cookie = "expires=" + now.toUTCString() + ";"
now = new Date();
now.setDate( now.getDate() + 30 );
document.cookie = "foo=bar;";
document.cookie = "expires=" + now.toUTCString() + ";"
Is it correct?
How to set another value with an expiration date for 30 days for example?
I think that approach is correct.
Based on: How can I set a cookie to expire after x days with this code I have? :
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
Note, that setTime() and getTime() work on milliseconds.
And a few words from me: as javascript's Date sucks, I recommend using moment.js library when working with dates, it's brilliant.
Ok, i found my reply here with the function "setCookie". I've specify differents values and it's working.
http://www.w3schools.com/js/js_cookies.asp

jQuery Format Time

I have a jQuery script that receives a string in milliseconds inside a parameter, like this:
params.tweetDate='77771564221';
What I need to do is to create a jQuery function that will be able to format this milliseconds string in a USA time, like 10.00 AM or 10.00 PM.
Is there a jQuery function that is able to do this?
Please help.
Thanks
There is Date object in pure javascript, no jQuery needed.
http://www.javascriptkit.com/jsref/date.shtml
Example:
var time = new Date(params.tweetDate),
h = time.getHours(), // 0-24 format
m = time.getMinutes();
// next just convert to AM/PM format (check if h > 12)
No, there's no jQuery function for this. You can use
JavaScript's own Date object, using the getHours() and getMinutes() functions, handling the AM/PM thing yourself (e.g., hours >= 12 is PM), padding out the minutes with a leading 0 if minutes is less than 10, etc. Also note that if hours is 0, you want to make it 12 (because when using the AM/PM style, you write midnight as "12:00 AM", not "0:00 AM").
DateJS, an add-on library that does a huge amount of date stuff (although sadly it's not actively maintained)
PrettyDate from John Resig (the creator of jQuery)
To use just about any of those, first you have to turn that "milliseconds" value into a Date object. If it's really a "milliseconds" value, then first you parse the string into a number via parseInt(str, 10) and then use new Date(num) to create the Date object representing that point in time. So:
var dt = new Date (parseInt(params.tweetDate, 10));
However, the value you've quoted, which you said is a milliseconds value, seems a bit odd — normally it's milliseconds since The Epoch (Jan 1, 1970), which is what JavaScript uses, but new Date(parseInt("77771564221", 10)) gives us a date in June 1972, long before Twitter. It's not seconds since The Epoch either (a fairly common Unix convention), because new Date(parseInt("77771564221", 10) * 1000) gives us a date in June 4434. So the first thing to find out is what that value actually represents, milliseconds since when. Then adjust it so it's milliseconds since The Epoch, and feed it into new Date() to get the object.
Here is a function for you:
function timeFormatter(dateTime){
var date = new Date(dateTime);
if (date.getHours()>=12){
var hour = parseInt(date.getHours()) - 12;
var amPm = "PM";
} else {
var hour = date.getHours();
var amPm = "AM";
}
var time = hour + ":" + date.getMinutes() + " " + amPm;
console.log(time);
return time;
}
You may call the function in any approach like:
var time = timeFormatter(parseInt("2345678998765"));
take a look at timeago: this is a jquery plugin used exactly for this purposes.
Using T.J.'s solution this is what I ended up with.
var date = new Date(parseInt("77771564221", 10));
var result = new Array();
result[0] = $.datepicker.formatDate('DD, M, d, yy', date);
result[1] = ' ';
if (date.getHours() > 12) {
result[2] = date.getHours() - 12;
} else if (date.getHours() == 0 ) {
result[2] = "12";
} else {
result[2] = date.getHours();
}
result[3] = ":"
result[4] = date.getMinutes();
if (date.getHours() > 12) {
result[5] = " pm";
} else {
result[5] = " am";
}
console.log(result.join(''));

Javascript Date Plus 2 Weeks (14 days)

I use this to get the date:
var currentTime = new Date()
var month = currentTime.getMonth() + 1
var day = currentTime.getDate()
var year = currentTime.getFullYear()
alert(month + "/" + day + "/" + year);
How can I add 2 weeks ? So instead of showing 10/13/2011, to show 10/27/2011 etc
Here is the fiddle: http://jsfiddle.net/25wNa/
I want the one input to have +14 days and the other +21
Note: I'd like the format to be > 10/13/2011 <.
12096e5 is a magic number which is 14 days in milliseconds.
var fortnightAway = new Date(Date.now() + 12096e5);
jsFiddle.
var currentTime = new Date();
currentTime.setDate(currentTime.getDate()+14);
Try this:
currentTime.setDate(currentTime.getDate()+14);
have made a fidle for you http://jsfiddle.net/pramodpv/wfwuZ/
Date.prototype.AddDays = function(noOfDays) {
this.setTime(this.getTime() + (noOfDays * (1000 * 60 * 60 * 24)));
return this;
}
Date.prototype.toString = function() {
return this.getMonth() + "/" + this.getDate() + "/" + this.getFullYear().toString().slice(2);
}
$(function() {
var currentTime = new Date();
alert(currentTime.AddDays(14));
});
12096e5 is a kind of magic number. Just 14 days in milliseconds in exponential notation.
This number is the result of 1000[ms] * 60[s] * 60[m] * 24[h] * 14[d] saved in exponential notation.
You can check it if you type Number('12096e5'). You will get 1209600000 [ms] which is exactly 2 weeks in milliseconds. The exponential notation makes it obscure.
You can write any other number in exponential notation to make the life of your fellow developers more interesting.
Date object has constructor which accepts milliseconds as an argument which argument can be in exponential notation.
var d = new Date(milliseconds);
var afterTwoWeeks = new Date(+new Date + 12096e5);
var afterTwoWeeks = new Date(+new Date + 1209600000);
Both are the same.
Well, JS times are in millisecond, so adding two weeks would be a case of working out what two weeks is in milliseconds, and adding that value.
var twoWeeks = 1000 * 60 * 60 * 24 * 14;
var twoWeeksTime = new Date(new Date().getTime() + twoWeeks);
var formattedDate = twoWeeksTime.getDate() + '/' + (twoWeeksTime.getMonth()+1) + '/' + twoWeeksTime.getYear();
Of course, this method falls down if you need to add months, since they're variable in length, but it's fine for adding days and weeks.
Alternatively, you use the DateJS library, which has functionality for exactly this kind of thing (plus loads more).
With DateJS, your code could look like this:
var twoWeeksTime = Date.today().add({ days: 14 });
var formattedDate = twoWeeks.TimetoString('dd/MM/yy');
Hope that helps.
Add or Subtract 2 weeks from current date
Below code example give output in YYYY-MM-DD format
If condition is added in the string to concatenate 0 with Month and Day which is less than 10.
var twoWeeks = 1000 * 60 * 60 * 24 * 14;
var twoWeeksTime = new Date(new Date().getTime() + twoWeeks); /* Add or Subtract here*/
var formattedDate = (twoWeeksTime.getFullYear()) + '-' +
((twoWeeksTime.getMonth()+1) < 10 ? "0"+(twoWeeksTime.getMonth()+1): (twoWeeksTime.getMonth()+1)) + '-' +
(twoWeeksTime.getDate() < 10 ? "0"+(twoWeeksTime.getDate()): (twoWeeksTime.getDate()));
document.body.innerHTML = formattedDate;
add the following prototype method
Date.prototype.addDays = function(days) {
this.setDate(this.getDate()+days);
}
and than its very simple to use,
currentTime.addDays(5);
If you are formatting a javascript date in a particular format, then I think you can have a look at this script http://blog.stevenlevithan.com/archives/date-time-format. All you would need to do after including the script is this new Date(+new Date + 1000* 60 * 60 * 24 * 14).format('dd/mm/yyyy') and you would get the output "27/10/2011"
The script is pretty small, just above 1KB minified. This is the link to a working fiddle http://jsfiddle.net/naryad/GufvT/

Categories

Resources