How do I compare dates in Javascript? - javascript

I have the following situation:
I have a certain function that runs a loop and does stuff, and error conditions may make it exit that loop.
I want to be able to check whether the loop is still running or not.
For this, i'm doing, for each loop run:
LastTimeIDidTheLoop = new Date();
And in another function, which runs through SetInterval every 30 seconds, I want to do basically this:
if (LastTimeIDidTheLoop is more than 30 seconds ago) {
alert("oops");
}
How do I do this?
Thanks!

JS date objects store milliseconds internally, subtracting them from each other works as expected:
var diffSeconds = (new Date() - LastTimeIDidTheLoop) / 1000;
if (diffSeconds > 30)
{
// ...
}

what about:
newDate = new Date()
newDate.setSeconds(newDate.getSeconds()-30);
if (newDate > LastTimeIDidTheLoop) {
alert("oops");
}

You can do like this:
var dateDiff = function(fromdate, todate) {
var diff = todate - fromdate;
return Math.floor(diff/1000);
}
then:
if (dateDiff(fromdate, todate) > 30){
alert("oops");
}

Create a date object and use setSeconds().
controlDate = new Date();
controlDate.setSeconds(controlDate.getSeconds() + 30);
if (LastTimeIDidTheLoop > controlDate) {
...

Related

postman: How to add minutes to a dateTime while looping with JS?

I am trying to add 15 mins to a dateTime(2100-01-04T08:00:00) while looping.
For each run I want to add 15 minutes , so it would be 2100-01-04T08:15:00 , 2100-01-04T08:30:00 and so on…
I know I can do the below:
var moment = require('moment');
moment().add(15, 'minutes').toISOString();
But this will add 15 minutes to the current moment time but I want to add 15 minutes to 2100-01-04T08:00:00.
Is this possible in postman?
You can easily create an addMinutes() function to add a number of minutes to a date, you can then use a while loop to loop until a specified end date is reached.
In the example below, we'll add 15 minutes to the date until the end date is reached.
function addMinutes(date, minutes) {
let newDate = new Date(date);
newDate.setMinutes(newDate.getMinutes() + minutes);
return newDate;
}
let date = new Date('2100-01-04T08:00:00');
let endDate = new Date('2100-01-04T09:00:00');
let deltaMinutes = 15;
while (date <= endDate) {
console.log(date.toLocaleString('en-US'));
date = addMinutes(date, 15);
}
.as-console-wrapper { max-height: 100% !important; }
You can achieve this without using any third party libraries like momentJs.
The default javascript Date object has methods for getting the minutes property for a date object - getMinutes() and also another method for updating this minutes property - setMinutes().
Combining them both, you can achieve your required answer.
let x = new Date('2100-01-04T08:00:00')
for(let i = 0 ; i < 5; i ++){
x.setMinutes(x.getMinutes()+15);
console.log(x)
}
P.S, remove 'postman' from your question. It has nothing to do with the problem you are facing.

How to get the difference in time using javascript?

im trying to get the current time timeNow in javascript and at the end of the script get
timeEnd which is when the script finished executing for example:
newDate = new Date();
timeNow = newDate.getTime();
for(i=0; i < 5; i ++){
console.log("printing" + i);
}
timeEnd = timeNow - newDate.getTime();
console.log(timeEnd);
i want to get the time it took to excute this script in seconds or milliseconds, but the result is 0. i don't see why, can you help me thanks.
The Date object does not keep ticking once it's constructed, it only represents a single instant in time.
You need to re-evaluate the time at the end of the script and then compare that value with the first one.
Note that on modern ES5 browsers you can use the "static" Date.now() function to get the current time. This is less expensive that constructing a whole new Date object. On older browsers you can emulate this function with this shim:
Date.now = Date.now || function() {
return +(new Date);
};
At which point the required code becomes:
var start = Date.now();
// do your stuff here
...
var end = Date.now();
var elapsed = end - start;
FWIW, your simple loop reports 2ms when run on the Chrome console on my laptop.
This happens because you create only a single Date object. These don't change; you will have to do:
timeEnd = timeNow - new Date().getTime();
(note the blank between new and Date)
var t = new Date().getTime();
// code
console.log(new Date().getTime() - t);
Because it takes less than a millisecond to perform 5 iterations I would imagine.
you can use
starttime = Number(new Date());
endtime = Number(new Date());
I actually don't think it is iterating in less than an millisecond. It think the problem is that when you call newDate.getTime() repeatedly it returns the same value each time. The object, once you create it, is set at the time it was created. You'll need to create a new Date() object to compare the original against.
From my Firebug Console:
>>> d = new Date()
Date {Thu Aug 23 2012 10:45:52 GMT-0600 (Mountain Daylight Time)}
>>> d.getTime()
1345740352582
>>> d.getTime()
1345740352582
>>> d.getTime()
1345740352582
>>> d.getTime()
1345740352582
I can assure you that I didn't manually make the calls to d.getTime() in less than a millisecond.
Basically, Do this
newDate = new Date();
timeNow = newDate.getTime();
for(i=0; i < 50; i++){
console.log("printing" + i);
}
futureDate = new Date()
timeEnd = futureDate.getTime();
timeLength = timeEnd - timeNow;
console.log(timeLength);

How do I compare the speed of two Javascript functions?

I have some Javascript that is reading in some XML. There is an older function which was used to create a JSON object from that data, and I've written a new function that I hope will create that JSON object faster.
What is the easiest and best way to determine which function is performing faster? It's a decent amount of data, so it's somewhat important to know.
Thanks.
You could use console.time("ID"); and console.timeEnd("ID"); (info here), and look the results in the Chrome Developer Tools or Firebug like so:
console.time("oldFunc");
//oldfunc();
console.timeEnd("oldFunc");
console.time("newfunc");
//newfunc();
console.timeEnd("newfunc");
Also, you could use jsperf
Some info on this and code sample here
var startDate = new Date();
// execute your tasks here
var endDate = new Date();
var timeTaken = endDate.getTime() - startDate.getTime();
alert('Time take to execute the script is '+timeTaken+' milliseconds');
(new Date).getTime();
This is how you get current time in milliseconds. Do that before and after execution of code, subtract and you have execution time in miliseconds.
Sample:
var start=(new Date).getTime();
//call your code
alert('Code took '+((new Date).getTime()-start)+'ms');
If your code organisation allows, you can make your call in a for loop, repeating n (let's say 1000) times and divide the time by n at the end.
This way you get the average speed, which is especially helpful if you function varies a lot (like network calls).
I like John Resigs way of testing the performance of a function:
function runTest(name, test, next){
var runs = [], r = 0;
setTimeout(function(){
var start = Date.now(), diff = 0;
for ( var n = 0; diff < 1000; n++ ) {
test();
diff = Date.now() - start;
}
runs.push( n );
if ( r++ < 4 )
setTimeout( arguments.callee, 0 );
else {
done(name, runs);
if ( next )
setTimeout( next, 0 );
}
}, 0);
}
Is this in the browser or server-side?
If it's server-side, I'd recommend using your shell scripting tool of choice to do the benchmarking (linux has time, windows has...whatever windows has).
If it's in the browser, then you can always wrap a certain number of iterations (10,000 is usually enough) in:
var start = new Date.getTime();
var runs = 10000;
while (runs) {
// do stuff here
runs--;
}
console.log('Finished in ' + (new Date.getTime() - start) + ' ms.');
var d1 = new Date();
function1();
var d2 = new Date();
console.log("Function 1 : ", d2.getTime() - d1.getTime());
function2();
var d3 = new Date();
console.log("Function 2 : ", d3.getTime() - d2.getTime());

Why doesn't this method for getting the difference between two dates work?

I am trying to test whether certain time has elapsed. I use javascript.
Both examples use this variable:
var delete_after = 2 /*minutes*/ * 60 /*seconds*/ * 1000/*miliseconds*/; // [miliseconds]
This works:
var now = new Date();
var now_t = now.getTime();
var then = new Date(x.time); // x.time is string with a time
var then_t = then.getTime();//).getTime();
if (now_t - then_t > delete_after) {
alert("deleted");
}
This does not:
if (Date().getTime() - Date(x.time).getTime() > delete_after) {
alert("deleted");
}
I belived them to be equivalent, but they are not. I checked precedence, in the end it appears I have to call new to create a variable. It seems to impossible to call (new Date().getTime()). Please, would You be so kind to explain why it can not be written the second way?
Date().getTime()
is not the same as
(new Date()).getTime()
Date(x.time).getTime()
is not the same as
(new Date(x.time)).getTime()
Well, if you want to do it in short, just do it like this:
if ((new Date()).getTime() - (new Date(x.time)).getTime() > delete_after) {
alert("deleted");
}
Your example didn't work because object has to be instantiated before you perform any function call on it.
getTime is a function of date objects, not of the Date() function, so you have to call Date() to get a date object, and then call getTime on it.
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date
This would do it all in one go, but it's a bit confusing
(new Date()).getTime()

how to update time regularly?

function timeClock()
{
setTimeout("timeClock()", 1000);
now = new Date();
alert(now);
f_date = now.getDate()+" "+strMonth(now.getMonth())+" "+now.getFullYear()+" / "+timeFormat(now.getHours(), now.getMinutes());
return f_date;
}
<span class="foo"><script type="text/javascript">document.write(timeClock());</script></span>
alert(now); gives me the value every second but it is not updated in the html. How can I update the time on the html without refresh the page?
There are a number of mistakes in your code. Without the use of var infront of your variable declarations, you leak them into the global scope.
Also, the use of document.write is discouraged.
Here's how I would do it:
JavaScript:
function updateClock() {
var now = new Date(), // current date
months = ['January', 'February', '...']; // you get the idea
time = now.getHours() + ':' + now.getMinutes(), // again, you get the idea
// a cleaner way than string concatenation
date = [now.getDate(),
months[now.getMonth()],
now.getFullYear()].join(' ');
// set the content of the element with the ID time to the formatted string
document.getElementById('time').innerHTML = [date, time].join(' / ');
// call this function again in 1000ms
setTimeout(updateClock, 1000);
}
updateClock(); // initial call
HTML:
<div id="time"> </div>
setInterval(expression, timeout);
The function setTimeout is intended for a single timeout, so using setInterval would be a more appropriate option. SetInterval will run regularly without the additional lines that Ivo's answer has.
I would rewrite Ivo's answer as follows:
JavaScript:
function updateClock() {
// Ivo's content to create the date.
document.getElementById('time').innerHTML = [date, time].join(' / ')
}
setInterval(updateClock, 1000);
Try it out yourself! https://jsfiddle.net/avotre/rtuna4x7/2/
x = document.getElementsByTagName('SPAN').item(0);
x.innerHTML = f_date;
try putting this code block instead of return statement, i haven't test it but it will probably work
There may be something in timeago jQuery plugin you can hook into, but I haven't honestly tried...
http://timeago.yarp.com/
$('span.foo').html(f_date);
place this inside your timeclock() function
untested
function timeClock()
{
setTimeout("timeClock()", 1000);
now = new Date();
alert(now);
f_date = now.getDate()+" "+strMonth(now.getMonth())+" "+now.getFullYear()+" / "+timeFormat(now.getHours(), now.getMinutes());
$('span.foo').html(f_date);
}
I'd use setInterval rather than setTimeout:
https://developer.mozilla.org/en/DOM/window.setInterval
I think your setTmeout function has the wrong variables, the first one should be a function not a string, that confused me for a bit. Basically you need to write to the span tag when you run the function.
I created a jQuery version in a fiddle to demonstrate what I mean. Didn't have your strMonth function but you get the idea. I also changed the alert to console.log but you can remove that line.
http://jsfiddle.net/5JWEV/
Straigt Javascript time format / update
1: create month converter func
2: create time func
3: create update func
4: create outPut func
// month converter from index / 0-11 values
function covertMonth(num){
let months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
// look into index with num 0-11
let computedRes = months[num];
return computedRes;
}
// time func
function Time(){
// important to get new instant of the Date referrance
let date = new Date();
this.time = date.toLocaleTimeString();
this.year = date.getUTCFullYear();
this.day = date.getUTCDate();
this.month = date.getUTCMonth();
this.currentTime = date.toLocaleTimeString() + ' ' + covertMonth(this.month) + ' ' + this.day + ' ' + this.year;
return this.currentTime;
}
function timeOutPut(){
let where = document.getElementById('some-id');
where.textContent = Time(); // 1:21:39 AM Dec 17 2017
}
// run every 5secs
setInterval(timeOutPut, 5000);
I used #soloproper setInterval concept #Ivo Wetzel overall answer, my update is all about formatting the time as required. Reduced Programming Lines
<div id="liveClock"> </div>
$(document).ready(function () {
updateClock();
});
function updateClock() {
document.getElementById('liveClock').innerHTML = new Date().format("dd/MMMM/yyyy hh:mm:ss tt");
}
setInterval(updateClock, 1000);
function timeClock()
{
setTimeout("timeClock()", 1000);
now = new Date();
alert(now);
f_date = now.getDate()+" "+strMonth(now.getMonth())+" "+now.getFullYear()+" / "+timeFormat(now.getHours(), now.getMinutes());
document.getElementById("foo").innerHTML = f_date;
}
<span id="foo"></span>

Categories