Increment a var by one every 24 hours from a specific date - javascript

I've never used Javascript before (or any other programming language) so sorry for asking this question because im sure it's very simple.
What I want to do is set a date in Javascript, then increment it by one every 24 hours. So three days after the date is set, 3 is displayed in the HTML (not the date itself). And after 100 days, 100 is displayed.
Thank you.

You have to create two date objects, one representing your initial date, and another one representing right now. Then, calculate the difference:
// Calculate days since Dec 1st 2012
var initialDate = new Date(2012, 11, 1); // Attention: month is zero-based
var now = Date.now();
var difference = now - initialDate;
var millisecondsPerDay = 24 * 60 * 60 * 1000;
var daysSince = Math.floor(difference / millisecondsPerDay);
alert(daysSince); // 80
http://jsfiddle.net/PmYFc/

If you are looking to show how many days the page has been open, you want to use the setInterval function: https://developer.mozilla.org/en-US/docs/DOM/window.setInterval.
So, if your HTML element looked like <span id='example'>0</span>, your JS might look like this:
var date = 0,
element = document.getElementById("example");
setInterval(function(){
date++;
element.innerText = date;
}, 1000 * 60 * 60 * 24); //milliseconds, seconds, minutes, hours
Though, it seems unlikely any page would sit unrefreshed for any significant length of time. If you need to persist the date variable beyond page refreshes you could look into localstorage.

Related

Need help subtracting time and date with Google SCRIPT

I have this code here:
var date = a.created_at_timestamp.substring(0,10)
var time = a.created_at_timestamp.substring(11,19)
And both these values return strings with these values:
date = 2020-05-19 //
Time = 17:00:08
I need to subtract 3 hours since it's coming in GMT time and I'm on GMT-3. Therefore, I thought about adding them together, subtracting three hours, and putting them apart again. Something like:
Orig Date: 20/05/19 //
Orig Time: 20:15:19
Time + Date: 20/05/19 20:15 //
Time + Date - 3h: 20/05/19 17:15
New Date: 20/05/19 00:00 //
New Time: 17:15:19
I tried converting it to milliseconds as suggested in other post here, doing with formulas, where a function would trigger formulas adding both cells, which I was able to do, but couldn't tear them apart together. In addition, if possible, I'd like to do it inside the script.
Can someone help me with that?
I'm new at this and I'm somewhat used to VBA. Tried some things from VBA, but they don't really apply here.
Instead of having separate strings for date and time, it'd likely be easier to just create a new Date object with both combined.
var dateTime = new Date(a.created_at_timestamp.substring(0,19));
You can then subtract 3 hours by doing:
var timeOffset = 3 * 60 * 60 * 1000; // 3hrs of millis
var offsetDate = new Date(dateTime.getTime() - timeOffset);

set a time interval based on current date Object (javascript)

So I am currently using the Google Calendar API, specifically the freebusy query (as seen here https://developers.google.com/google-apps/calendar/v3/reference/freebusy/query).
The request body requires a 'timeMin' and 'timeMax'. And here comes my question...
How would I set these two values dynamically based off the current datetime. Basically use the current datetime to set an interval, say an hour before now, and an hour after now.
I have seen other stackoverflow posts (Subtracting hours from date string) on how to setHours by getHours but the problem with this method seems to be that it alters the current time instead of creating a new instance.
Also I need to keep the resulting min and max datetimes in ISOstring format (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString) because this is what is used in Google Calendar API request body.
I believe you're looking for something like this:
var now = new Date();
var msNow = now.getTime(); // total mil1iseconds since 1970/01/01
var timeMax = new Date(msNow + 60 * 60 * 1000); // "now" plus one hour
var timeMin = new Date(msNow - 60 * 60 * 1000); // "now" minus one hour
console.log(now);
console.log(timeMin);
console.log(timeMax);

Jquery Countdown To Next Wednesday 11pm

I need to write a function that will take a javascript date object in UTC time. It needs to find the difference in seconds from the given date and next (or coming) Wednesday 11pm then put it in a countdown object. Once the the timer hits 0, I need it to restart again. I know I have to use the getDay() function somehow but I'm unsure of how to go about this.
Logic and Code
You don't need jQuery for the countdown timer itself. The date object is part of plain vanilla JavaScript.
For UTC, you'll want to use the getUTCDay() method.
Assuming givenDate is a Date object, the following would calculate how many days until the coming Wednesday (day 3).
var daysUntilTarget = (3 - givenDate.getUTCDay() + 7) % 7;
If given date is on a Wednesday, the above will return 0 and you'll need to determine if target time has passed yet. You could use something like this:
var daysUntilTarget,
targetDay = 3,
targetHour = 23,
targetMinute = 0,
targetSecond = 0;
if (
targetDay == givenDate.getUTCDay() &&
targetHour * 3600 +
targetMinute * 60 +
targetSecond * 1 <
givenDate.getUTCHours() * 3600 +
givenDate.getUTCMinutes() * 60 +
givenDate.getUTCSeconds() * 1 +
givenDate.getUTCMilliseconds() / 1000
) {
//given date is after target time on target day
daysUntilTarget = 7;
}
Use the setUTCDate() and setUTCHours methods to set the target date and time.
var targetDate = new Date(givenDate);
targetDate.setUTCDate(givenDate.getUTCDate() + daysUntilTarget);
targetDate.setUTCHours(targetHour, targetMinute, targetSecond);
Use the getTime() method to get a timestamp for both the given date and the target date. Then you can calculate the difference between these and divide by 1000 to get the number of seconds.
var countdownSeconds = (targetDate.getTime() - givenDate.getTime()) / 1000;
The following will convert the total seconds into days, minutes, and seconds. You can then write these to an element in your HTML.
var daysLeft, hoursLeft, minutesLeft, secondsLeft;
secondsLeft = parseInt(countdownSeconds);
daysLeft = parseInt(secondsLeft / 86400);
secondsLeft = secondsLeft % 86400;
hoursLeft = parseInt(secondsLeft / 3600);
secondsLeft = secondsLeft % 3600;
minutesLeft = parseInt(secondsLeft / 60);
secondsLeft = parseInt(secondsLeft % 60);
Be sure to convert countdownSeconds to an integer before doing further calculations with it. Otherwise, you may get undesired results due to floating point math. For example,
0.009 / 86400 = 1.0416666666666665e-7;
parseInt(1.0416666666666665e-7) = 1;
parseInt(0.009 / 86400) = 1; //probably not what you were expecting
Countdown Timer
To update the timer, you could decrement a counter or use the client machine's clock to keep time.
The counter method is not as accurate as the clock method because the former doesn't take into account the amount of time it takes for the code to run. I've noticed a 3-second loss over a half-hour period. Adjusting the loop interval will not fix this since different browsers run code at different speeds. And code may run slower for other reasons such as when machine is low on memory.
The client machine's time may not be accurate to begin with. However, the server time can be compared to the client time initially to calculate an offset. Then the client time can be used as a counter rather than an absolute value. The draw back is that if the client time changes, it will affect the countdown. Note that time zone changes and changes due to Daylight Saving Time will not affect the countdown since they do not affect the timestamp.
Examples
I've created two fiddles using the code described above.
Countdown Timer (Using Counter)
Countdown Timer (Using Clock)

How to get date from previous sunday using new Date()

whats the best way to get previous sunday using new Date()?
any ideas? sorry newbie here*
Since it's not a trivial task, here's the algorithm I suggest for you:
Create a Date object
Get the current day of week from the object
If it's zero (Sunday) set it to seven
Subtract that many days from the date*
Done!
*This works really well thanks to some rather clever implementation. If you subtract 4 days from February 2nd, the result is January 29th.
Now it's up to you to write some code ;)
Many tutorials on the web will show you how to use Date.getDay() that returns the day of the week (from 0 to 6).
Then substract one day to your date until you get the expected result.
Here is my variant:
var dateNow = new Date();
var dateToday = new Date(dateNow.getFullYear(), dateNow.getMonth(), dateNow.getDate());
var dateSunday = new Date(dateToday.getTime()-dateToday.getDay()*24*3600*1000);
in dateSunday you'll get date object on sunday start.
var yourDate = new Date(Date.now() - ((new Date().getDay() + 7) * 24 * 60 * 60 * 1000));
Date.now() gets the current date down to the millisecond, which makes it easy to perform mathematical calculations.
new Date().getDay() + 7, like one of the previous posters suggested finds the current day (0-based) and add 7 to that in order to subtract however many days we are from the most recent sunday, minus one week.
24 * 60 * 60 * 1000 ensures that we are subtracting that many full days (in milliseconds) away from our current day in order to find last Sunday.
Or, you could write some algorithm too.
Best of luck friendo. :]

how to calculate number of days between today and given date and code for getTime()?

I want to calculate number of days between today and a given date and check whether how many days remaining until today or how many days past from today.
var today = new Date();
var date_to_reply = new Date('2012-10-15');
var timeinmilisec = today.getTime() - date_to_reply.getTime();
console.log( Math.floor(timeinmilisec / (1000 * 60 * 60 * 24)) );
this gives me 5 as answer but how should i get (-5) since the date_to_reply is 5days past from today?
is this the correct way to calculate any given date?
Regards
What you are doing is correct: You want to calculate the difference (as number of days) between two dates. A difference can't be smaller than zero.
Although your date_to_reply is already in the past, theres still a 5 day difference.
So, everythings fine - it's the correct way.
EDIT:
If you want a negative value as result, try this:
var today = new Date();
var date_to_reply = new Date('2012-10-15');
var timeinmilisec = date_to_reply.getTime() - today.getTime();
console.log( Math.ceil(timeinmilisec / (1000 * 60 * 60 * 24)) );
Remember you need to Math.ceil the final result instead of rounding it down with Math.floor().
If you want the value to be negative (indicating date_to_reply is in the past) you should subtract the past date from the current: date_to_reply.getTime() - today.getTime().
Check this link for ways to calculate more diffentiated results.
If you swap the order of the dates, you'll get the negative number you want.
Better yet you could write a function that does this.
It could subtract the first parameter from the second.
The second parameter could default to today.
function diffDates(dateOne, dateTwo) {
if (typeof dateTwo === 'undefined') {
dateTwo = new Date();
}
return dateOne.getTime() - dateTwo.getTime();
}
It would be better to have the function operate on numbers rather than dates.
That would be more flexible, but I'm typing on an iPad right now!
Its obvious because today's date is greater than the previous. So either you need to make it negative on your own or use this
var timeinmilisec = date_to_reply.getTime()-today.getTime();

Categories

Resources