I need to find the difference, in hours, between two values(t1 and t2)
t1(Now) code:
<td><!--tc:minutes--></td>
t2(then) code:
<td><!--tc:time.cost--></td>
For example t1 is 1:11 (1 hours, 11 minutes) and t2 is 1:05 (1 hours, 5 minutes)
How can I get the remaining time? 0:06 (0 hours, 6 minutes)? I think I need JavaScript function like HoursBetween in Delphi..
// using Date objects
var start = Date.now();
// the event to time goes here:
doSomethingForALongTime();
var end = Date.now();
var elapsed = end - start; // elapsed time in milliseconds
// using built-in methods
var start = new Date();
// the event to time goes here:
doSomethingForALongTime();
var end = new Date();
var elapsed = end.getTime() - start.getTime(); // elapsed time in milliseconds
// to test a function and get back its return
function printElapsedTime(fTest) {
var nStartTime = Date.now(),
vReturn = fTest(),
nEndTime = Date.now();
console.log('Elapsed time: ' + String(nEndTime - nStartTime) + ' milliseconds');
return vReturn;
}
yourFunctionReturn = printElapsedTime(yourFunction);
Related
I am working on a project that requires a time in the future to be set using the Date object.
For example:
futureTime = new Date();
futureTime.setHours(futureTime.getHours()+2);
My questions is; once the future date is set, how can I round to the closest full hour and then set the futureTime var with it?
For example:
Given 8:55 => var futureTime = 9:00
Given 16:23 => var futureTime = 16:00
Any help would be appreciated!
Round the minutes and then clear the minutes:
var date = new Date(2011,1,1,4,55); // 4:55
roundMinutes(date); // 5:00
function roundMinutes(date) {
date.setHours(date.getHours() + Math.round(date.getMinutes()/60));
date.setMinutes(0, 0, 0); // Resets also seconds and milliseconds
return date;
}
The other answers ignore seconds and milliseconds components of the date.
The accepted answer has been updated to handle milliseconds, but it still does not handle daylight savings time properly.
I would do something like this:
function roundToHour(date) {
p = 60 * 60 * 1000; // milliseconds in an hour
return new Date(Math.round(date.getTime() / p ) * p);
}
var date = new Date(2011,1,1,4,55); // 4:55
roundToHour(date); // 5:00
date = new Date(2011,1,1,4,25); // 4:25
roundToHour(date); // 4:00
A slightly simpler way :
var d = new Date();
d.setMinutes (d.getMinutes() + 30);
d.setMinutes (0);
Another solution, which is no where near as graceful as IAbstractDownvoteFactory's
var d = new Date();
if(d.getMinutes() >= 30) {
d.setHours(d.getHours() + 1);
}
d.setMinutes(0);
Or you could mix the two for optimal size.
http://jsfiddle.net/HkEZ7/
function roundMinutes(date) {
return date.getMinutes() >= 30 ? date.getHours() + 1 : date.getHours();
}
As a matter of fact Javascript does this default which gives wrong time.
let dateutc="2022-02-17T07:20:00.000Z";
let bd = new Date(dateutc);
console.log(bd.getHours()); // gives me 8!!!!!
it is even wrong for my local time because I am GMT+2 so it should say 9.
moment.js also does it wrong so you need to be VERY carefull
Pass any cycle you want in milliseconds to get next cycle example 1 hours
function calculateNextCycle(interval) {
const timeStampCurrentOrOldDate = Date.now();
const timeStampStartOfDay = new Date().setHours(0, 0, 0, 0);
const timeDiff = timeStampCurrentOrOldDate - timeStampStartOfDay;
const mod = Math.ceil(timeDiff / interval);
return new Date(timeStampStartOfDay + (mod * interval));
}
console.log(calculateNextCycle(1 * 60 * 60 * 1000)); // 1 hours in milliseconds
I have a cron job running on the server that performs some action every 6 hours UTC.
On the client page, I want to show a countdown that shows the time remaining for the next cron job to run.
If it was running at midnight I could have done
function timeToMidnight() {
var now = new Date();
var end = moment().endOf("day");
return end - now + 1000;
}
But I am not able to figure out how to do this for 6 hourly UTC (1200 AM, 0600 AM, 1200 PM, 0600 AM)
You can calculate it quite easily without moment
const timeToNextRun = (start) => {
const sixHoursInMs = 6 * 3600 * 1000;
let remainingTime = sixHoursInMs - (start.getTime() % sixHoursInMs);
return remainingTime;
};
let now = new Date();
let countdown = timeToNextRun(now);
console.log(`Setting timer for ${countdown}ms - ${new Date(now.getTime() + countdown).toISOString()}`);
Just count down to any of these
const getDates = () => {
const d = new Date()
const utcDate = new Date(Date.UTC(d.getFullYear(),d.getMonth(), d.getDate(),6,0,0))
return [utcDate,new Date(utcDate.getTime() + (21600000)),new Date(utcDate.getTime() + (21600000*2)),new Date(utcDate.getTime() + (21600000*3))]
}
console.log(getDates())
function returntime() {
var start = new Date().getSeconds();
var end = new Date().getSeconds();
var totaltime = end - start;
document.getElementById("Answer").innerHTML = totaltime;
}
The totaltime return 0 but when i put start or end it shows the output.
There is no delay between both statements.
var start = new Date().getSeconds();
var end = new Date().getSeconds();
You ask for seconds. The code runs faster than a second.
For example, you get 9 seconds at the start and 9 seconds in the end.
If you ask for the milliseconds you will see that you will have a different result.
I was creating a webpage and I would like to receive assistance in that. I need a text to popup when the UTCHours and UTCMinutes are equal to specific values. I want something like this. This is like the model , not actual code.
h = utcTime
m = utcminutes
if (h=x and m=y)
{
function myFunction();
}
Surely I wont do everything for you, but here you go. A base to start from.
// The button functionality
const $ = (x) => document.getElementById(x);
$('start').addEventListener('click', ()=>{
startTime();
});
$('stop').addEventListener('click', ()=>{
stopTime();
});
// The timer
// set variables
let date,
start,
stop;
function startTime() {
date = new Date(); // get current date.
start = date.getTime(); // get time from current date
// Just output
document.getElementById("showStart").innerHTML = start;
}
function stopTime() {
date = new Date(); // get current date.
stop = date.getTime(); // get time from current date
// just output
document.getElementById("showStop").innerHTML = stop;
document.getElementById("difference").innerHTML = stop-start;
}
jsfiddle
I was bored so here you go.
// The button functionality
const $ = (x) => document.getElementById(x);
$('setAlert').addEventListener('click', ()=>{
setAlert(3); // alert in x seconds.
});
// set variables
let date,
target,
stop,
interval = 1; // integer.
function setAlert(time) {
date = new Date(); // get current date.
target = date.getTime() + ( (time * 1000) - ((interval * 1000) +1000) ); // sets the time it should alert.
/*
* time -1 because it's a 1s interval, that means when it reaches x = y it will alert 1s later by the next "check". This why you need to subtract 1s.
* (time-1)*1000 is because the getTime returns time in ms not in seconds. You would need to make it setAlert(3000),
* i made it bit easier by multiplying the value by 1000 = ms.
*/
// The loop that checks time
setInterval(function(){ // This function makes the "checking each X ms"
if(stop !== target){ // Check if time was reached.
stopTime(); // Check time
}else{
alert("TIME IS OVER"); // When time is reached do this.
}
}, interval*1000); // Refreshes the time each second.
// Just output
document.getElementById("showTarget").innerHTML = target+(interval*1000); // Because the target time has "minus" in it (line 16) it needs to be added to show the real target time.
}
function stopTime() {
date = new Date(); // get current date.
stop = date.getTime(); // get time from current date
// just output
document.getElementById("showStop").innerHTML = stop;
// document.getElementById("difference").innerHTML = stop-target;
}
jsfiddle v2
function displayAlert(hour,minute){
//create a new Date Object(Current Date and Time)
var date = new Date();
// getUTCHours getUTCMinutes are inbuilt methods
// for getting UTC hour and minute by comparing it with timezone
var utcHour = date.getUTCHours();
var utcMinutes = date.getUTCMinutes();
//display alert when utc hour and minute matches sired time
if(utcHour == hour && utcMinutes == minute){
alert(utcHour + " : " + utcMinutes)
}
}
displayAlert(18,31)
setInterval(function(){
now = new Date();
hours = now.getUTCHours();
mins = now.getUTCMinutes();
executeFunctionIfEqualToDefined(hours, mins);
},60000); // this block will run every 60000 milli seconds i.e 60 seconds =1 min
function executeFunctionIfEqualToDefined(hours, mins){
if(hours === x && mins === y){
//execute your code here
}
}
lol sorry i posted it accidentally
I'm new to JavaScript and i'm trying to make a simple countdown script that should show the difference between the end date and today's server date.
here is a great example of what i'm trying to do http://moblog.bradleyit.com/2009/06/javascripting-to-find-difference.html
The only thing i want to add is another variable with a calculated seconds. How can i do that?
Here is the code:
var today = new Date();
var Christmas = new Date("12-25-2009");
var diffMs = (Christmas - today); // milliseconds between now & Christmas
var diffDays = Math.round(diffMs / 86400000); // days
var diffHrs = Math.round((diffMs % 86400000) / 3600000); // hours
var diffMins = Math.round(((diffMs % 86400000) % 3600000) / 60000); // minutes
alert(diffDays + " days, " + diffHrs + " hours, " + diffMins + " minutes until Christmas 2009 =)");
You have two issues with this code:
1: You need to use a date that will be accepted across browsers so it needs to be formatted with / instead of -.
2: You are rounding, which when rounding up will give you inaccurate numbers. All numbers need to be rounded down. Here is a function do do so:
var roundDown = function(num){
var full = num.toString();
var reg = /([\d]+)/i;
var res = reg.exec(full);
return res[1];
}
So your final code should look like this:
var roundDown = function(num){
var full = num.toString();
var reg = /([\d]+)/i;
var res = reg.exec(full);
return res[1];
}
var today = new Date(); // date and time right now
var goLive = new Date("06/01/2013"); // target date
var diffMs = (goLive - today); // milliseconds between now & target date
var diffDays = roundDown(diffMs / 86400000); // days
var diffHrs = roundDown((diffMs % 86400000) / 3600000); // hours
var diffMins = roundDown(((diffMs % 86400000) % 3600000) / 60000); // minutes
var diffSecs = roundDown((((diffMs % 86400000) % 3600000) % 60000) / 1000 ); // seconds
var endDate = new Date(year, month, day, hours, minutes, seconds, milliseconds);
var today = Date.now()
var timeLeft = endDate - today // timeLeft would be in milliseconds
// Parse this into months, days, hours, ...
Put this in a function and set it up to be called every second or so using setInterval.
This should get you started with the JavaScript date object and it's associated methods.
http://www.w3schools.com/jsref/jsref_obj_date.asp
Also, look up the setInterval() method, that will allow you to fire code in set intervals (for example, updating the countdown text).