I'm trying to use the pattern described here: How to add number of days to today's date?
My goal is to start an animation at a date one week before a certain event, in this case the launch of Sputnik. My code is:
var SputnikLaunchDate = new Date(1957, 9, 4); //The first event of insterest in the simulation.
var earliestAnimationDate = new Date();
earliestAnimationDate.setDate(SputnikLaunchDate.getDate() - 7); //Start 1 week before then
When I do this in the Firefox debugger, the variable SputnikLauchDate is correct (1957-10-04T05:00:00.000Z). However, earliestAnimationDate ends up being 2015-05-28T18:49:54.313Z and I have no idea why. Can someone explain to me what I'm doing wrong?
The problem is that setDate sets the number of days relative to the current time, but when you constructed earliestAnimationDate you didn't give it any information, so it was set to today's date. Pass in SputnikLaunchDate.getTime() to initially copy that time into earliestAnimationDate (or else just put new Date(1957, 9, 4) again, of course).
var SputnikLaunchDate = new Date(1957, 9, 4);
var earliestAnimationDate = new Date(SputnikLaunchDate.getTime());
earliestAnimationDate.setDate(SputnikLaunchDate.getDate() - 7);
Related
I am very new to JavaScript and had a question. I have done research and I just can't figure out why the following function isn't working for me. I am trying to establish Current Date and then getting various values from that value such as Current Date minus one year, Current Date plus one year, etc.
For Current Date minus year I have the following but it's not working (I would much prefer to have a one liner for other reasons:
var currentDateMinusOneYear = new Date(new Date().setFullYear(new Date().getFullYear() - 1));
console.log(currentDateMinusOneYear);
First we should get fullYear from a new Date, decrease by 1, set that as the year of a new Date. Then we wrap the whole thing in a Date constructor.
Console just returns an empty object. Not sure why. Please advise.
function datecheck(){
var dt1 = new Date();
dt1.setUTCFullYear("2017");
dt1.setUTCDate("1");
dt1.setUTCMonth("1");
alert(dt1.getUTCMonth());
}
When I execute this function I am getting 0 as alert but if setUTCMonth("2"). I am getting 2 in alert. Similarly if 3,4,5,6,7,8... is given then it alerts with same month that is passed then what is problem with January month?
But also I have observed that if
function datecheck(){
var dt1 = new Date();
dt1.setUTCFullYear("2017");
dt1.setUTCMonth("1");
dt1.setUTCDate("1");
alert(dt1.getUTCMonth());
}
Behaviour change it start alerting 0 when 1 is passed. I am totally confused what is going on...
Can anyone tell me where I am going wrong.
Thanks in advance.
You have a couple of problems. First off, mutating Date objects that way is inadvisable unless you really know what you are doing. Its better to pass the desired parameters to the constructor:
var jan1 = new Date(2017, 0, 1);
Note that I passed in zero. That's because unlike every other date-related counting, in JavaScript months go from 0-11.
Secondly, you are ignoring the impact of timezones. JavaScript constructs Date objects in the local timezone. For example, I'm GMT -5 at the moment.
If I do the following in my browser's console:
var dec31 = new Date(2016, 11, 31, 20); // 20hr == 8pm
dec31.getMonth(); // 11
dec31.getUTCMonth(); // 0
The five hour offset pushes the UTC time into the next month.
I am making a simple web app using javaScript. At one part I want an event to fire when the date changes (i.e., 4th Jan becomes 5th Jan).
This is what I am doing:
window.onload=function(){
var today = new Date();
var tommorow = new Date(today.getFullYear(),today.getMonth(),today.getDate()+1);
var timeToMidnight = (tommorow-today)/60;
var timer = setTimeout(function(){console.log("this");},timeToMidnight);
}
Anyhow, the problem I am facing is that the function is getting executed around 30-40 seconds before it is actually midnight. What's wrong? What should I do?
When you convert dates to numbers, you get milliseconds (see Date.prototype.valueOf).
That's the unit required by setTimeout. So you don't have to divide.
Change
var timeToMidnight = (tommorow-today)/60;
to
var timeToMidnight = (tommorow-today);
I need to use JavaScript to display the next event on a recurring weekly basis on a website. Let's say we start an event every 10am every Saturday - I'll need it to display that the next event begins on "Saturday, (Month) (Date) at 10am".
The only thing that I need to be dynamic on the website is the date of the next event (both month and date).
Idea 1: One way I started thinking about it I would need to and have some sort of a starting reference calendar date from where the schedule starts, and then some pattern of n-days to calculate the upcoming dates from that starting point and compare those against todays date, then display the result of the next in the sequence
Idea 2: Instead of using a pattern of N-days to calculate from a hard-coded reference point, what if I coded the day of the week the event occurs and check against that, calculating the date by comparing the days of the week and adding to todays date (would have to account for rollovers at 28/30/31 days and a way to account for which months max out at which number)
Maybe I'm way off-base in my thinking, but any help here would be appreciated. I'm learning JavaScript and coming from an HTML+CSS background using jQuery plugins if that helps frame your answer in a way I'll grasp.
Here is a rough solution that may work. It's just general code that you will need to debug but I think it's a good starting point! Date() is a built-in JavaScript object.
var today = new Date();
//var dd = today.getDate(); *just some sample functions of Date()*
//var mm = today.getMonth()+1; *January is 0!*
if(today.getDay() == 6) alert('it is saturday');
// today.getDate() < 8 *this can be used to check where in the month a day falls
// if you want only first, second, third, etc., Saturday
Please let me know if this helps at all!
You could use rSchedule for this (a javascript recurrence library which I maintain).
Example:
Let's say we start an event every 10am every Saturday
import { Schedule } from '#rschedule/rschedule';
import { StandardDateAdapter } from '#rschedule/standard-date-adapter';
const schedule = new Schedule({
rrules: [{
frequency: 'WEEKLY',
// the hypothetical start datetime of your recurring event
start: new Date(2019, 5, 15, 10),
}],
dateAdapter: StandardDateAdapter,
});
The only thing that I need to be dynamic on the website is the date of the next event (both month and date).
// get standard javascript iterator for occurrences starting after now
const iterator = schedule.occurrences({
start: new Date()
})
// the next date
const nextDate = iterator.next().value;
// or iterate over all future occurrences
for (const date of iterator) {
// do stuff...
}
I have been trying to make a quick reference sheet to use for work, and have been using this as a way to start trying to learn JavaScript.
I've been stumped on how to display the date in dd/mm/yyyy for the 4th Friday (or any day) from the current date. If anyone can point me in the right direction it would be greatly appreciated
The idea is to use setDate() for date addition. The following code should set you there:
<html>
<script>
// You might want to make a function out of this, btw.
dayWeWant = 5; // Friday
today = new Date();
// So you want the fourth friday, eh?
// remember friday is 5 for getDay
if (today.getDay() < dayWeWant) { nextFri = 7 - (today.getDay() - dayWeWant) } // days remaining
else { nextFri = dayWeWant - today.getDay(); }
// If today IS friday, you want 4 instead of 3. Of course,
// 3 can also be made into a "constant" variable, such as howManyWeeks or something
threeMore = nextFri + 3 * 7; // three more weeks
nextDate = new Date();
nextDate.setDate(today.getDate() + threeMore);
alert (nextDate);
</script>
</html>
Code is intentionally well annotated and not as efficient it can be (and the constant numbers aren't nice - you can make them into parameters of some function) - but does the trick. From here, minor optimizations are possible (but not as readable, IOHO)
Hope This Helps,
TG