jQuery Time difference - javascript

Hi am making some time calculation in jquery. Do you think am using the best way?
<table width="100%" border="0" cellpadding="0">
<tr>
<td>Departure Time</td>
<td>Arrival Time</td>
<td>Difference</td>
</tr>
<tr>
<td><input name="departure" type="text" class="std1" id="departure" size="10" alt="time"/></td>
<td><input name="arrival" type="text" class="std1" id="arrival" size="10" alt="time"/></td>
<td><input name="duration" type="text" class="std" id="duration" size="10" readonly="readonly" alt="time"/></td>
</tr>
</table>
function hour2mins(timestr) {
var spltd = timestr.split(":");
if (spltd.length == 2) {
return parseInt(parseInt(spltd[0] * 60) + parseInt(spltd[1]));
} else {
return false;
}
}
function mins2hour(instr) {
var hourstr = parseInt(instr / 60);
if (hourstr.toString().length == 1) {
hourstr = "0" + (hourstr + '');
}
var minstr = parseInt(instr % 60);
if (minstr.toString().length == 1) {
minstr = "0" + (minstr + '');
}
return hourstr + ':' + minstr;
}
function tdiff(t1, t2) {
var t1 = hour2mins(t1);
var t2 = hour2mins(t2);
var ret = mins2hour(parseInt(t2 - t1));
if (t2 < t1) {
ret = mins2hour(parseInt(parseInt(t2 + 1440) - t1));
}
return ret;
}
$(function() {
$("input.std1").keyup(function(b) {
$("#duration").val(tdiff($("#departure").val(), $("#arrival").val()));
});
});
link : http://jsfiddle.net/xmQD7/1/

Your code won't work for the following input: "07:09", "07:07". The problem is with your parseInt statement.
You should always pass in 10 as the second parameter, so that it's parsed as a decimal value.
return parseInt(parseInt(spltd[0] * 60, 10) + parseInt(spltd[1], 10));
Also, you don't need to wrap the addition of two parsed integers in a parseInt, so that would be just
return parseInt(spltd[0] * 60, 10) + parseInt(spltd[1], 10);
In mins2hour, you don't need a parseInt here:
var hourstr = parseInt(instr / 60);
and here:
var minstr = parseInt(instr % 60);
I'm guessing you wanted a string as this point (as your var name suggests), so that should have been
var hourstr = "" + (instr / 60);
var minstr = "" + (instr % 60);
There are a few more unnecessary uses of parseInt in your code. I suggest you read the documentation on parseInt - https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/parseInt

Related

JavaScript Time picker insert from real time

In a row I have a clock, which shows the time when I log in. How I can make it real, so its ticking all the time and shows real time? Please see picture ( row with 20.03.21 22:25 )
cms with time
<input type="text" class="light1" name="Date" value="[[:Date:]]" /><br/>
<input type="text" class="light1" id="txt" name="Now" readonly="readonly" value="[:NOW:]" />
<span style="position:relative; top:0px; left:0px;">↑</span>
If you want a text input to update every second with the time, you could implement something like this:
<input type="text" id="myTime" />
<script>
window.onload = function () {
setInterval(function () {
var newDate = new Date();
document.getElementById('myTime').value = newDate.toLocaleString();
}, 1000);
}
</script>
Code taken from Clock and date javascript
const pad = num => ("0" + num).slice(-2);
const timedate = () => {
const currentTime = new Date(new Date().getTime() + diff);
let hours = currentTime.getHours();
const minutes = pad(currentTime.getMinutes());
const seconds = pad(currentTime.getSeconds());
const d = currentTime.getDate();
const day = pad(d);
const month = pad(currentTime.getMonth() + 1);
const yyyy = currentTime.getFullYear();
/* let dn = "PM"
if (hours <= 12) dn = "AM";
if (hours >= 12) hours -= 12;
if (hours == 0) hours = 12; */
hours = pad(hours);
timeOutput.value = "" +
yyyy + "/" + month + "/" + day +
" " +
hours + ":" +
minutes + ":" +
seconds// + dn;
}
let timeOutput;
let serverTime;
let diff;
window.addEventListener("load", function() {
timeOutput = document.getElementById("timedate");
serverTime = new Date("2020/03/21 22:23:24");// change to new Date("[[:Date:]]"); for example
diff = new Date().getTime() - serverTime.getTime();
setInterval(timedate, 1000);
});
<input type="text" id="timedate" class="light1" name="Date" value="" /><br/>

javascript simple loop calculation

function calc() {
var aa = document.getElementById("aa").value;
var bb = document.getElementById("bb").value;
var cc = document.getElementById("cc").value;
var time = 1;
var dd = document.getElementById("dd").value / 365;
first = 1 + ((bb / 100) / cc);
second = cc * time;
result = aa * Math.pow(first, second);
bb_earn = aa * Math.pow(first, second) - aa;
final = Number(aa) + Number(bb_earn);
var r = "";
var lastTotal = aa;
for (var i = 0; i < dd; i++) {
var newTotal = Number(lastTotal) + Number(bb_earn);
zz = +newTotal;
lastTotal = newTotal;
r += i + 1 + ") " + aa + "---" + zz + "---" + final + "<br/>";
r += "";
}
document.getElementById("table").innerHTML += r;
}
<div> A - <input type="text" id="aa" value="12000" /></div>
<div> B - <input type="text" id="bb" value="20" /></div>
<div> C - <input type="text" id="cc" value="1" /></div>
<div> D - <input type="text" id="dd" value="1825" /></div>
<div> <input type="button" value="Get" onclick="calc();" /></div>
<br/><br/>
<div id="table"></div>
I am trying to loop the default value, 20% of default value and sum of default value plus 20% of default value. In next row, default value should be previous final column sum value. I tried above javascript calculation to achieve the desired result. But, I messed up..
Output result is:
1) 12000---14400---14400
2) 12000---16800---14400
3) 12000---19200---14400
4) 12000---21600---14400
5) 12000---24000---14400
But, Output should be:
1) 12000---2400---14400
2) 14400---2880---17280
3) 17280---3456---20736
4) 20736---4147.20---24883.20
5) 24883.20---4976.60---29859.80
It's a bit hard to figure out what you're trying to achieve with the code, based on what you write. It could be written a lot more simple if you merely wanted to take the previous total and add 20% each time. You don't explain what time variable does and what the #cc element does.
Regardless of that, this should output the result you expect.
function calc() {
var aa = document.getElementById("aa").value;
var bb = document.getElementById("bb").value;
var cc = document.getElementById("cc").value;
var dd = document.getElementById("dd").value / 365;
var r = "";
var lastTotal = Number(aa);
for (var i = 0; i < dd; i++) {
var ratio = ((bb / 100) / cc);
var addition = lastTotal * ratio;
var newTotal = lastTotal + addition;
r += i + 1 + ") " + lastTotal + "---" + addition + "---" + newTotal + "<br/>";
r += "";
lastTotal = newTotal;
}
document.getElementById("table").innerHTML += r;
}
<div> A - <input type="text" id="aa" value="12000" /></div>
<div> B - <input type="text" id="bb" value="20" /></div>
<div> C - <input type="text" id="cc" value="1" /></div>
<div> D - <input type="text" id="dd" value="1825" /></div>
<div> <input type="button" value="Get" onclick="calc();" /></div>
<br/><br/>
<div id="table"></div>
There is nothing wrong with the for next loop
But i guess everything is wrong with your formulas.
<!DOCTYPE HTML>
<html>
<head>
<title>Untitled</title>
</head>
<body>
<div> A - <input type="text" id="aa" value="12000" /></div>
<div> B - <input type="text" id="bb" value="20" /></div>
<div> C - <input type="text" id="cc" value="1" /></div>
<div> D - <input type="text" id="dd" value="1825" /></div>
<div> <input type="button" value="Get" onclick="calc();" /></div>
<br/><br/>
<div id="table"></div>
<script>
function calc(){
var aa = document.getElementById("aa").value*1.0;//ensure that we use numbers and not strings
var bb = document.getElementById("bb").value*1.0;
var cc = document.getElementById("cc").value*1.0;
var time = 1.0;
var dd = document.getElementById("dd").value*1 / 365;
first = 1 + ((bb / 100) / cc);//first = 1.2 bb 20 ,cc 1
second = cc * time; // 1*1=1
// i guess here you make a mistake or choose the wrong test datas
var fact=Math.pow(first, second) // fact = 1.2^1
result = aa * fact; //result 14400 = 12000*1.2;
bb_earn = aa * fact - aa; // bb_earn = 1.2 * 12000 -12000 = .2*12000 =2400
final = aa + bb_earn; //final =12000 + 2400 = again 14400
var zz=0;
var r = "";
var lastTotal = aa;
for (var i = 0; i < dd; i++) {
// as you could see thére is by this numbers NO chance to get something like -4147.20
// there are NO AFTER DIGITS in this calculation
//based on the fact result not possible
var newTotal = Number(lastTotal) + Number(bb_earn);
zz = newTotal;
lastTotal = newTotal;
r += i + 1 + ") " + aa + "---" + zz + "---" + final + "<br/>";
r += "";
}
document.getElementById("table").innerHTML += r;
}
</script>
</body>
</html>

Taking inputted value and putting it on a timer

So I'm making a countdown timer and I'm trying to figure out how to grab the values inputted through the form and put them in the display so the timer can count down from that.
Here's the (probably vastly wrong) JS function I wrote:
function changeTime() {
var h = parseInt(hrs.value);
var m = parseInt(mns.value);
var s = parseInt(scs.value);
if (h < 10) {
h = 0 + h;
};
if (m < 10) {
m = 0 + m;
};
if (s < 10) {
s = 0 + s;
};
$("#time").html() = h + ":" + m + ":" + s;
}
$("#change").click(function() {
changeTime();
})
Here's the form part of the HTML:
<form id="choose">
<input type="text" id="hrs" name="hrs" size="2" maxlength="2" placeholder="h"/>
<input type="text" id="mns" name="mns" size="2" maxlength="2" placeholder="m"/>
<input type="text" id="scs" name="scs" size="2" maxlength="2" placeholder="s"/>
</form>
Here's the whole fiddle. I know the alignment is off, but I'll fix it, I just want help with the JS. Thanks!
The html() setter should be work only if you added HTML string as the argument in the method.
$("#time").html( h + ":" + m + ":" + s );
Although you need to use string concatenation instead of Number addition.
if (h < 10) {
h = '0' + h;
//--^-^--- this should be string
};

How to add two input time values and display it in another input box?

I am getting two durations, current time and previous time from user. now, i want to calculate the total time show it on the third textbox.
<p><span>Current Duration</span><input id="txt1" onblur="sum();" type="text" autocomplete="off" name="current_duration" value="" /></p>
<p><span>Previous Duration</span><input id="txt2" onblur="sum();" type="text" autocomplete="off" name="previous_duration" value="" /></p>
<p><span>Total Duration</span><input id="txt3" type="text" readonly autocomplete="off" name="total_duration" value="" /></p>
<script>
function sum() {
var txtFirstNumberValue = document.getElementById('txt1').value;
var txtSecondNumberValue = document.getElementById('txt2').value;
var result = parseInt(txtFirstNumberValue) + parseInt(txtSecondNumberValue);
if (!isNaN(result)) {
document.getElementById('txt3').value = result;
}
}
</script>
How can i implement the same? can you guys help me out?
Assumning the separator between time and minutes is '.', this will work. If another separator i needed, just replace the character in toTime() and fromTime()
<p><span>Current Duration</span><input id="txt1" onblur="sum();" type="text" autocomplete="off" name="current_duration" value="" /></p>
<p><span>Previous Duration</span><input id="txt2" onblur="sum();" type="text" autocomplete="off" name="previous_duration" value="" /></p>
<p><span>Total Duration</span><input id="txt3" type="text" readonly autocomplete="off" name="total_duration" value="" /></p>
<script>
function sum() {
var txtFirstNumberValue = document.getElementById('txt1').value;
var txtSecondNumberValue = document.getElementById('txt2').value;
var result = fromTime(txtFirstNumberValue) + fromTime(txtSecondNumberValue);
if (!isNaN(result)) {
document.getElementById('txt3').value = toTime(result);
}
}
function fromTime(time) {
var timeArray = time.split('.');
var hours = parseInt(timeArray[0]);
var minutes = parseInt(timeArray[1]);
return (hours * 60) + minutes;
}
function toTime(number) {
var hours = Math.floor(number / 60);
var minutes = number % 60;
return hours + "." + (minutes <= 9 ? "0" : "") + minutes;
}
</script>
JsFiddle
I have find this from SO.
You can try this:
function sum()
{
var datetime = document.getElementById('txt1').value;
var txtSecondNumberValue = document.getElementById('txt2').value;
var datetime = new Date(datetime).getTime();
var now = new Date(txtSecondNumberValue).getTime();
if( isNaN(datetime) )
{
return "";
}
console.log( datetime + " " + now);
if (datetime < now) {
var milisec_diff = now - datetime;
}else{
var milisec_diff = datetime - now;
}
var days = Math.floor(milisec_diff / 1000 / 60 / (60 * 24));
var date_diff = new Date( milisec_diff );
return days + "d "+ (date_diff.getHours() - 5) + "h " + (date_diff.getMinutes() - 30) + "m";
}

how to replace old div with a new one?

I want to close and create a new div when the countdown hits 0. My div looks like this
<div id="bij2">Test
<div id="bij2Blauw">
<table width="98%" border="0" align="center" cellpadding="0" cellspacing="0">
<tr>
<td colspan="3" class="titel">Resterende tijd</td>
</tr>
<tr>
<td height="25" colspan="3" align="center" valign="middle">
<input id="aktie2" type="text" class="countdownTekst" size="27" readonly="readonly">
<script language="javascript">
countdown(2012, 7, 29, 'aktie2', 'bij2')
</script>
</td>
</tr>
<tr>
<td height="60">
<input name="kopen1" type="submit" class="kopen" id="kopen1" value="Koop nu"
/>
</td>
<td height="60" colspan="2" align="right" valign="bottom">
<span class="euro">€</span>
<span class="prijs">14,95</span>
</td>
</tr>
</table>
</div>
</div>
This is the countdown
function countdown(yr, m, d, idCountdown, divId) {
var theyear = yr;
var themonth = m;
var theday = d;
var today = new Date();
var todayy = today.getYear();
if (todayy < 1000) todayy += 1900
var todaym = today.getMonth();
var todayd = today.getDate();
var todayh = today.getHours();
var todaymin = today.getMinutes();
var todaysec = today.getSeconds();
var todaystring = montharray[todaym] + " " + todayd + ", " + todayy + " " + todayh + ":" + todaymin + ":" + todaysec;
var futurestring = montharray[m - 1] + " " + d + ", " + yr;
var dd = Date.parse(futurestring) - Date.parse(todaystring);
var dday = Math.floor(dd / (60 * 60 * 1000 * 24) * 1);
var dhour = Math.floor((dd % (60 * 60 * 1000 * 24)) / (60 * 60 * 1000) * 1);
var dmin = Math.floor(((dd % (60 * 60 * 1000 * 24)) % (60 * 60 * 1000)) / (60 * 1000) * 1);
var dsec = Math.floor((((dd % (60 * 60 * 1000 * 24)) % (60 * 60 * 1000)) % (60 * 1000)) / 1000 * 1);
var dag = "dagen";
if (dday <= 0 && dhour <= 0 && dmin <= 0 && dsec <= 0) {
document.getElementById(idCountdown).value = "voorbij";
$(document.getElementById(divId)).fadeOut(2000);
//removeElements(document.getElementById(divId));
setTimeout("creatediv(document.getElementById(divId))", 3000);
return;
} else if (dday <= 1) {
dag = 'dag';
}
document.getElementById(idCountdown).value = dday + ' ' + dag + ' ' + dhour + " uur " + dmin + " min " + dsec + " sec";
setTimeout(function () {
countdown(theyear, themonth, theday, idCountdown);
}, 1000);
}
So when the time is over it will fade out the div using jQuery. Then i want to create a new div. I use this:
function creatediv(id) {
var newdiv = document.createElement('div');
newdiv.setAttribute('id', id);
newdiv.className = 'newclass';
newdiv.style.float = "left";
newdiv.innerHTML = "nothing";
document.body.appendChild(newdiv);
alert(id + 'gemaakt');
}
But this creates a div at the bottom of the page and i want a new one at the same position as the div that fades out. What do i need to change?
Have you tried the replaceWith of jQuery?
It's really simple:
$('#bij2').replaceWith( newcontent );
You are not using jQuery at all in your code. The error you make is that you don't replace the node but rather append the new one after it. The function you are looking for is replaceChild.
node.replaceChild(oldNode, newNode)
If you wan to replace div 2 with suppose a div 3
<div id="1"><div id = "2"></div></div>
you can use
$("#1").html('<div id="3"></div>')
or you can use
$("#2").replaceWith('<div id="3"></div>')
You've said "using jQuery," but you don't seem to be using jQuery.
If you really are using / intend to start using jQuery, then Rahul's answer is what you want.
If not, then you're looking for parentNode, insertBefore, and removeChild, e.g.:
// Assuming olddiv refers to the old div
var parent = olddiv.parentNode;
parent.insertBefore(newdiv, olddiv);
parent.removeChild(olddiv);
That inserts the new div in front of the old one, then removes the old one.
So perhaps:
function replacediv(oldid, id) {
var newdiv = document.createElement('div');
newdiv.id = typeof id !== "undefined" ? id : oldid; // Use old ID if no new one specified
newdiv.className = 'newclass';
newdiv.style.float = "left";
newdiv.innerHTML = "nothing";
var olddiv = document.getElementById(oldid);
var parent = olddiv.parentNode;
parent.insertBefore(newdiv, olddiv);
parent.removeChild(olddiv);
alert(id + 'gemaakt');
}
...and then call it with the old ID and the new one.
As a side note: You don't have to use setAttribute for id. It's a reflected property on the element instance.

Categories