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);
Related
i am trying to get current date to compare and setting hours to zero but still getting time.
var today = new Date(new Date().setHours(0,0,0,0));
var todaynew = today.toISOString();
console.log(todaynew);
my output like :
2018-03-20T18:30:00.000Z
I need to get date as it is but time 2018-03-20T00:00:00.000Z
When you create a new Date(), the time zone is that of the system. When you use toISOString(), the time is printed in UTC. This means that your code will print a different result when running on systems with different time zones (it prints 2018-03-20T23:00:00.000Z for me).
Instead of using setHours(), use setUTCHours().
var today = new Date(new Date().setUTCHours(0,0,0,0));
var todaynew = today.toISOString();
console.log(todaynew);
I am trying to setup a interval to run every morning at 0730. I am trying to use momentjs to accomplish this.
e.g:
current time - 0730 = how long to wait until it is time to run the function.
For some reason no matter how I manipulate the moment it seems to come back with some wonky math. For example it is currently 0616 in the morning and when I attempted to get this to do the math it came back with a 6hr difference not just over an hour.
var endOfShift = moment('0730', 'HHmm').format(),
now = moment().utcOffset(-8).format(),
diff = moment(now).local() - moment(endOfShift).local();
console.log(endOfShift); // => 2019-12-20T07:30:00+00:00
console.log(now); // => 2019-12-20T06:11:38-08:00
console.log(diff); // => 24098000 milliseconds = 6.6938888889hrs
I have tried removing the utcOffset from now which then the out put for the time/date incorrect. I have tried adding utcOffset to the endOfShift variable. No matter how I mess with the utc it still seems to = around 6hrs when it should be about 1ish. I have tried just removing the utcOffset from everything and just let it do its thing and it still gets the math wrong.
I have also tried moment's diff method w/ similar results.
What am I missing?
-Adam
I think you can achieve this with something like this
const now = moment();
let targetTime = moment('07:30', 'hh:mm'); // could be in past or in future
if (targetTime.isBefore(now)) {
targetTime = targetTime.add(1, 'day'); // add one day if waiting for tomorrows time
}
const diff = targetTime.diff(now);
console.log(diff);
const otherDiff = targetTime - now;
console.log(otherDiff);
The values for diff and otherDiff should be equal so it's up to you which one you prefer.
I've been working on calculating the total hours, minutes and seconds between two times using the moment.js library. The problem I have is that the calculations don't recognise that it's a day and return more hours than what is there. I'll give you an example:
I want to know how many hours are between 21:00 and 06:00, the answer is 9, however, the calculation brings back -15, this is also technically correct. I need to tell moment that it should use a day to calculate this value. I can get it to work if I use a DateTime picker but I don't want to use that as the user is only required to provide a time.
My application uses KendoUI for MVC and moment.js, moment.duration.format.js and moment.range.js
Here is my code which will return -15
#(Html.Kendo().TimePicker().Name("start").Value("21:00"))
#(Html.Kendo().TimePicker().Name("end").Value("06:00"))
<button class="btn btn-default btn-success" onclick="calc()">Plot</button>
Here is the javascript that works with this.
function calc() {
window['moment-range'].extendMoment(moment);
console.clear();
var dformat = "HH:mm:ss";
var start = $("#start").data("kendoTimePicker").value();
var end = $("#end").data("kendoTimePicker").value();
var startTime = moment(kendo.toString(start));
var endTime = moment(kendo.toString(end));
var duration = moment.duration(endTime.diff(startTime));
var hours = parseInt(duration.asHours());
console.log(hours);
}
If we change this to use DateTimePicker instead, it understands there is a day and calculates 9 hours. So how do I get around this? How can I achive this without using a datetime picker? Can I leaverage moment.js startof day or something?
Thanks to #VincenzoC I have managed to fix this problem. Here is the code which checks if the end time is before the start time and if it is, add a single day. This means the resulting time is accurate.
var startTime = moment(start);
var endTime = moment(end);
if (endTime.isBefore(startTime))
{
endTime.add(1, 'd');
}
//
//After the above condition has been passed, calculate the difference
var duration = moment.duration(endTime.diff(startTime));
//
//Any format you want
console.log(duration.format("HH"))
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);
I am fairly new to HTML and Javascript, so I'm trying to make a small incremental game as practice. This is the code I am trying to use to calculate the automatic gains / second, as well as adjust accordingly for when the tab isn't in focus and setInterval stops running.
var startTime = new Date();
var endTime = new Date();
var interval = 100;
window.setInterval(function(){
startTime.getTime();
var timeDiff = startTime - endTime;
do{
document.getElementById('woodAmount').innerHTML = Math.floor(user.wood += (user.WPS/10));
document.getElementById('oilAmount').innerHTML = Math.floor(user.oil += (user.OPS/10));
document.getElementById('goldAmount').innerHTML = Math.floor(user.gold += (user.GPS/10));
document.getElementById('coalAmount').innerHTML = Math.floor(user.coal += (user.CPS/10));
timeDiff -= interval;
}while (timeDiff >= interval);
endTime.getTime();
}, interval);
For some reason, this code doesn't adjust for the time when the tab is not focused, but it works as expected when it is in focus.
As you can see here, I set the interval to 100 milliseconds, and I divide the resources / second (user.WPS) by 10.
However, when I set the interval to 1 second (1000 milliseconds) and don't divide the resources / second by 10, it works as expected all the time, and properly adjusts for the time that the tab isn't focused.
Can anyone offer an explanation as to why it works when using full-second intervals, but won't when using 100 millisecond intervals?
.getTime() gets the time that is already in the Date object at the time it was created or whenever the time was last set in the date object. It does NOT get the current time.
If you want to get the current time, I often use this little function:
function now() {
return new Date().getTime();
}
Or, if you don't need IE8 support, then you can use Date.now().
In addition, the getTime() method pulls the time out of the data object and returns it from that method call. If you want to use it, you have to put it somewhere after calling .getTime().