Purpose of date.getTime in the expires flag of the cookie? - javascript

I have a line of code that sets a cookie with an expiry date that looks like this.
var date = new Date();
date.setTime(date.getTime() + 1000*60*60*24*365);
var expires = "; expires=" + date.toGMTString();
What I'm trying to do is understand what each number represents. I know thats its just adding milliseconds to the time object but what does each one represent is the question.

1000 milliseconds in a second
60 seconds in a minute
60 minutes in an hour
24 hour in a day
365 days in a year
So, you'll get the quantity of milliseconds in a year.

var date = new Date(); // date object (now on this computer)
date.setTime( // change the time
date.getTime() // now in milliseconds since 1970
+ 1000 // milliseconds in a second
* 60 // seconds in a minut
* 60 // minutes in an hour
* 24 // hours in a day
* 365 // approximate days in a year. Total ~ number of milliseconds in a year
);
var expires = "; expires=" +
date.toGMTString(); // format the time to what the cookie likes
Please read
Date
toGMTString
for more information

1000 millicesonds times 60 seconds times 60 minutes times 24 hours times 365 days. It's a year.

Think about it like this:
1000*60*60*24*365
1000 // Converts milliseconds into seconds
60 // Converts seconds into minutes
60 // Convert minutes into hours
24 // Converts hours into days
365 // Convert days into year

1000 milliseconds per second,
60 seconds per minute,
60 minutes per hour,
24 hours in a day,
365 days in a year,
So it is adding the number of milliseconds in a year, advancing the time by a year

Related

How to countdown and divide the time into segments?

I wish to do a countdown to a specific date and hour (January 10, 2018, 19:30). Which in large part I am able to do. Below code shows the remaining days, hours, minutes and seconds.
The tricky bit is to get certain periods of time. The countdown should respond to the following:
1. on the deadline day and hour show the message 'Now going live'. Which is 10 January 2018 19:30.
2. That same day but BEFORE 19:30 it should say 'Going live tonight'
3. The complete day before the deadline day (from 00:00 to 23:59) it should say 'last day'
4. The complete days before that it should say 'many days to go'
Step 1 and 2 I managed, but I'm having trouble getting the complete day before the deadline day and the complete days before that. That's because I'm not able to define the complete day before the deadline day (and the days before that). Because it counts '1 day' as 1 day before 10 January 19:30 (so it also takes those hours/minutes of 19:30 into account).
Step 1 and 2 I managed in the if-loop, but I can't figure out how to do step 3 and 4. Step 3 should say something like 'count one day, but before 10 January 2018 00:00. So it should subtract that 19:30 to get to 9 januari 2018 00:00-23:59. And the same for step 4. Can someone fix my code?
// Get todays date and time
var now = new Date().getTime();
// Set the date we're counting down to
var countDownDate = new Date("Januari 10, 2018 19:30").getTime();
// Find the distance between now an 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);
// Display the result
this.timeleft.text = days + "d " + hours + "h " + minutes + "m " + seconds + "s ";
// countdown day 19:30
if ((days == 0) && (hours == 0) && (minutes == 0)) {
this.countdown.text = "NOW GOING LIVE!";
// countday day 00:00 - 19.30
} else if ((days == 0) && (hours <= 19) && (minutes <= 30)) {
this.countdown.text = "GOING LIVE TONIGHT!";
// 9 January 00:00 - 23:59
} else if ((days <= 1) && (hours >= 19) && (minutes >= 30)) {
this.countdown.text = "LAST DAY";
// days before 10 January
} else if (days >= 1) {
this.countdown.text = "MANY DAYS TO GO";
}
Since the "deadline" is hard-coded, you can hard-code everything and end up with something very simple:
var now = new Date().getTime();
var lastDayThreshold = new Date("January 9, 2018 00:00").getTime();
var liveTonightThreshold = new Date("January 10, 2018 00:00").getTime();
var countDownDate = new Date("January 10, 2018 19:30").getTime();
if (now < lastDayThreshold) this.countdown.text = "MANY DAYS TO GO";
else if(now < liveTonightThreshold) this.countdown.text = "LAST DAY";
else if(now < countDownDate) this.countdown.text = "LIVE TONIGHT";
else this.countdown.text = "NOW GOING LIVE";
Alex's answer was indeed what I was after. Those 'treshhold times' did the trick. Was thinking about improving it though as now I have to hard-code three dates/times. Preferably I would like to only specify the countDownDate date/time. And then let both Threshold dates calculate themselves. I tried to do that in a way, but ran into a problem. I know how to specify one day (1000 * 60 * 60 * 24), so I could subtract this 'oneday' value to get to the day before. But I wasn't able to calculate the milliseconds for the specified time 19:30. In order to read the miilliseconds since the beginning of January 10 until January 10 19:30. If I were able to do that it would look something like this (though I know this is incorrect, but you'll get the idea):
var oneday = 1000 * 60 * 60 * 24;
var countDownDate = new Date("January 10, 2018 19:30").getTime();
var lastDayThreshold = new Date(countDownDate - oneday "00:00").getTime();
var liveTonightThreshold = new Date(countDownDate "00:00").getTime();
You'll see my problem: for lastDayTreshold I could subtract one day of the countdowndate but then it would consider that 19:30 the previous day, not 00:00. And for liveTonightThreshold I also couldn't specify that I mean 00:00 of the countdowndate.
Would there be a way of doing that? Then I would just have to specify the countdown day and time and the rest would figure them out themselves.

How to add 1 hour and 5 minutes in Javascript

I have a requirement to show the pop up of every 1 hour 5 seconds, have set the time for 1 hour, how to set a time for 1 hour 5 seconds using Javascript.
for 3 minutes set the time for 3 * 60 * 1000;
for 1 hour set the time for 1 * 60 * 60 * 1000;
how to be for 1 hour 5 minutes?
Use date object and it's methods. getTime() will get the current date in milliseconds and add appropriate milliseconds for 1 hour 5 minute (which is 65 minute), which will be 65 * 60 * 1000. And after use setTime() to create the date according to the milliseconds.
var date = new Date();
console.log(date);
date.setTime(date.getTime() + 65 * 60 * 1000);
console.log(date);
1 Hr s= (1 * 60 * 60* 1000)
5 Sec = (5*1000)
Then
1 Hrs 5 Sec = (1 * 60 * 60* 1000)+(5*1000)

Is there a method to convert miliseconds to years,months,days,minutes,seconds in JavaScript?

I am trying to compare 2 dates and represent the difference( converted to miliseconds) via years,months,days,minutes and seconds.I am new in JS,I looked up for a ready method to convert miliseconds to years,months,days, minutes, seconds but didn't find.Tell me please is there such method? If not how can I do that? Simply by dividing the difference and using reminder?Thank you in advance for help.
Without having a calendar and knowing the input dates, the best you can do is be approximate.
Here is a script that shows the time elapsed since midnight last night.
var diff = Date.now() - Date.parse("July 13, 2016");
var seconds = Math.floor(diff / 1000),
minutes = Math.floor(seconds / 60),
hours = Math.floor(minutes / 60),
days = Math.floor(hours / 24),
months = Math.floor(days / 30),
years = Math.floor(days / 365);
seconds %= 60;
minutes %= 60;
hours %= 24;
days %= 30;
months %= 12;
console.log("Years:", years);
console.log("Months:", months);
console.log("Days:", days);
console.log("Hours:", hours);
console.log("Minutes:", minutes);
console.log("Seconds:", seconds);
There is no inbuilt method to convert given millisecond to equivalent seconds, minutes, hours, days, months or years.
You will have to use math. Although you will only be able to convert accurately up to days. Months and years will vary as months are either 28, 29, 30 or 31 and there are leap years.
Consider having a look at http://momentjs.com/ before you write anything on your own, as you can do a lot more with this library like adding and subtracting days or hours etc

JavaScript difference between two Date()'s in months [duplicate]

This question already has answers here:
Difference between two dates in years, months, days in JavaScript
(34 answers)
Closed 8 years ago.
I am trying to make a website that tells you (in years, months, weeks, hours, minutes and seconds) how old you are. I have got all of them working apart from months and years. Once I get the months I will be able to get the years (hopefully), however I'm having trouble thinking of a way to get the months. For the others it was easy (once I had the seconds between the birth date and the current date I could just convert seconds to minutes, to hours, to days etc.), however for months I'm going to need to take into account the fact they are all different lengths, AND leap years (which currently does not affect the days either).
Hope this helps you out
// Set the unit values in milliseconds.
var msecPerMinute = 1000 * 60;
var msecPerHour = msecPerMinute * 60;
var msecPerDay = msecPerHour * 24;
// Set a date and get the milliseconds
var date = new Date('6/15/1990');
var dateMsec = date.getTime();
// Set the date to January 1, at midnight, of the specified year.
date.setMonth(0);
date.setDate(1);
date.setHours(0, 0, 0, 0);
// Get the difference in milliseconds.
var interval = dateMsec - date.getTime();
// Calculate how many days the interval contains. Subtract that
// many days from the interval to determine the remainder.
var days = Math.floor(interval / msecPerDay );
interval = interval - (days * msecPerDay );
// Calculate the hours, minutes, and seconds.
var hours = Math.floor(interval / msecPerHour );
interval = interval - (hours * msecPerHour );
var minutes = Math.floor(interval / msecPerMinute );
interval = interval - (minutes * msecPerMinute );
var seconds = Math.floor(interval / 1000 );
// Display the result.
document.write(days + " days, " + hours + " hours, " + minutes + " minutes, " + seconds + " seconds.");
//Output: 164 days, 23 hours, 0 minutes, 0 seconds.
Would you consider an external library? Check out http://momentjs.com/
You can easily do something like
date1.diff(date2, 'months')

Javascript Count Days From Today

I would like a simple text box input of a date in the past and then for it to display how many days it is from today's date. I have found several examples of how to use javascript to do it between two dates that you input, but not with only doing one date and today's.
The current date to track is 4/2/2010, but it will change over time.
If you don't care about the leap second (:)), you can simply subtract the current date from the date back then, which gets you the difference in milliseconds, and then divide the difference by the amount of milliseconds that fits in one day:
var then = new Date(2010, 03, 02), // month is zero based
now = new Date; // no arguments -> current date
// 24 hours, 60 minutes, 60 seconds, 1000 milliseconds
Math.round((now - then) / (1000 * 60 * 60 * 24)); // round the amount of days
// result: 712
Here is a script I use for countdown timers. You can take out whatever parts you dont need to display just a day, time etc.
dateFuture = new Date(2029,2,4,23,59,59);
function GetCount(){
dateNow = new Date();
//grab current date
amount = dateFuture.getTime() - dateNow.getTime();
//calc milliseconds between dates
delete dateNow;
// time is already past
if(amount < 0){
document.getElementById('countbox').innerHTML="Now!";
}
// date is still good
else{
days=0;hours=0;mins=0;secs=0;out="";
amount = Math.floor(amount/1000);//kill the "milliseconds" so just secs
days=Math.floor(amount/86400);//days
amount=amount%86400;
hours=Math.floor(amount/3600);//hours
amount=amount%3600;
mins=Math.floor(amount/60);//minutes
amount=amount%60;
secs=Math.floor(amount);//seconds
if(days != 0){out += days +" day"+((days!=1)?"s":"")+",<br />";}
if(days != 0 || hours != 0){out += hours +" hour"+((hours!=1)?"s":"")+",<br />";}
if(days != 0 || hours != 0 || mins != 0){out += mins +" minute"+((mins!=1)?"s":"")+",<br />";}
out += secs +" seconds";
document.getElementById('countbox').innerHTML=out;
setTimeout("GetCount()", 1000);
}
}
window.onload=function(){GetCount();}//call when everything has loaded
<div id="countbox"><div>

Categories

Resources