Computation in javascript using times - javascript

How to use times in javascript? Formula is 5+1000/1000+20000/10000+3000/10000*0.06 = 0.66 in calculator 5+1+2+3*0.6=0.66. I don't know if some of my computation is wrong or the code is wrong.
I try to search it but still same result, yet on calculator is different.
function calc() {
var today = new Date();
var month = today.getMonth(); // Returns 9
month = month + 1;
console.log(month); // Output: 9
var textValue3 = document.getElementById('input3').value;
var textValue2 = document.getElementById('input2').value
var textValue1 = document.getElementById('input1').value;
var basic = 5;
var rate_interest;
if (month == 1) {
rate_interest = 0;
} else if (month == 2) {
rate_interest = 0;
} else if (month == 3) {
rate_interest = 0.06;
} else if (month == 4) {
rate_interest = 0.08;
} else if (month == 5) {
rate_interest = 0.10;
} else if (month == 6) {
rate_interest = 0.12;
} else if (month == 7) {
rate_interest = 0.14;
} else if (month == 8) {
rate_interest = 0.16;
} else if (month == 9) {
rate_interest = 0.18;
} else if (month == 10) {
rate_interest = 0.20;
} else if (month == 11) {
rate_interest = 0.22;
} else if (month == 12) {
rate_interest = 0.24;
}
document.getElementById('output').value = (basic) + (textValue1 / 1000) + (textValue2 / 1000) + (textValue3 / 1000) * (rate_interest);
}

Your formula is completely broken.
An Input value will always be a String! It's your job as a developer to transform it into a Number using parseInt or parseFloat.
Remember:
On a calculator, if you do 1 + 2 * 5 ...if you take a close look it's a resolved sequence. Therefore 1 + 2 results in 3 and thenafter 3 * 5 results in 15.
On any better calculator you can also write compound expressions and also use Brackets ( )
In math, (therefore also in programming), if you do 1 + 2 * 5 it's just like writing this expression: 1 + (2 * 5) results in 11 - due to Operator Precedence.
const
EL_in1 = document.querySelector('#input1'),
EL_in2 = document.querySelector('#input2'),
EL_in3 = document.querySelector('#input3'),
EL_int = document.querySelector('#interests'),
EL_out = document.querySelector('#output');
const calc = () => {
const
basic = 5,
month = new Date().getMonth() + 1,
v1 = parseFloat(EL_in1.value),
v2 = parseFloat(EL_in2.value),
v3 = parseFloat(EL_in3.value),
rIt = (month < 3 ? 0 : month * 0.02).toFixed(2),
out = (basic + v1 / 1000 + v2 / 1000 + v3 / 1000) * rIt;
EL_int.value = rIt;
EL_out.value = out.toFixed(2);
}
[EL_in1, EL_in2, EL_in3].forEach(EL => EL.addEventListener("input", calc));
calc();
[type=number] {width: 45px;}
(
5 +
(<input id="input1" type="number" value="1000"> / 1000) +
(<input id="input2" type="number" value="2000"> / 1000) +
(<input id="input3" type="number" value="3000"> / 1000)
) *
<input id="interests" type="number" readonly> =
<input id="output" type="number" readonly>

Related

age calculator with javascript

I was trying to create an age calculator with javascript.There is a condition if the birthday input fileds are empty then it will give an error massage.but now even the filed are empty and click on the submite button it's submiting and giving an auot days month and year.How can I solve this issue.Here is my java script code
let presentdate = document.getElementById("pdate");
let presentmonth = document.getElementById("pmonth");
let presentyear = document.getElementById("pyear");
var date = new Date();
var pdate = date.getUTCDate(); //present date
var pmonth = 1 + date.getUTCMonth(); //present month
var pYear = date.getUTCFullYear(); // present year
var month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
// present date , month and year
presentdate.value = pdate;
presentmonth.value = pmonth;
presentyear.value = pYear;
// set conditions
function isNum(arg) {
var args = arg;
if (args == "" || args == null || args.length == 0) {
return false;
}
// argument to set only number in input
args = args.toString();
for (var i = 0; i < args.length; i++) {
if (
(args.substring(i, i + 1) < "0" || args.substring(i, i + 1) > "9") &&
args.substring(i, i + 1) != "."
) {
return false;
}
}
return true;
}
// check date.it will set the date between 1-31.
function checkday(aa) {
var val = aa.value;
var valc = val.substring(0, 1);
if (val.length > 0 && val.length < 3) {
if (!isNum(val) || val == 0) {
aa.value = "";
} else if (val < 1 || val > 31) {
aa.value = valc;
}
} else if (val.length > 2) {
val = val.substring(0, 2);
aa.value = val;
}
}
//check month.it will set month between 1-12.
function checkmonth(aa) {
var val = aa.value;
var valc = val.substring(0, 1);
if (val.length > 0 && val.length < 3) {
if (!isNum(val) || val == 0) {
aa.value = "";
} else if (val < 1 || val > 12) {
aa.value = valc;
}
} else if (val.length > 2) {
val = val.substring(0, 2);
aa.value = val;
}
}
function age() {
let bdate = +document.getElementById("date").value;
let bmonth = +document.getElementById("month").value - 1;
let byear = +document.getElementById("year").value;
if (bdate === "" || bmonth === "" || byear === "") {
document.getElementById("error").innerHTML = "Put Your Birthday";
return;
}else{
let current = new Date();
let birth = new Date(byear, bmonth, bdate);
let difference = current - birth;
let years = Math.floor(difference / (1000 * 60 * 60 * 24 * 365.25));
difference -= years * (1000 * 60 * 60 * 24 * 365.25);
let months = Math.floor(difference / (1000 * 60 * 60 * 24 * 30.4375));
difference -= months * (1000 * 60 * 60 * 24 * 30.4375);
let days = Math.floor(difference / (1000 * 60 * 60 * 24));
document.querySelector(".calc_result").style.display = "block";
document.getElementById(
"total_age"
).innerHTML = `${years} Years ${months} Months ${days} Days`;
calculateDaysLived();
calculateNextBirthday();
// remove error text
document.getElementById("error").innerHTML = "";
}
}
// total days
function calculateDaysLived() {
let today = new Date();
let birthdate = new Date(
document.getElementById("year").value,
document.getElementById("month").value - 1,
document.getElementById("date").value
);
let timeDifference = today - birthdate;
let daysLived = Math.floor(timeDifference / (1000 * 60 * 60 * 24));
document.getElementById("total_day").innerHTML =
"You lived " + daysLived + " days Since Your Birthday";
}
// next birtday
function calculateNextBirthday() {
let today = new Date();
let birthdate = new Date(
document.getElementById("year").value,
document.getElementById("month").value - 1,
document.getElementById("date").value
);
birthdate.setFullYear(today.getFullYear());
while (birthdate < today) {
birthdate.setFullYear(birthdate.getFullYear() + 1);
}
document.getElementById("next_bday").innerHTML =
"Your next birthday is on " + birthdate.toDateString();
}
You're converting date inputs to numbers and you're comparing them to an empty string. It's going to always be false:
if (bdate === "" || bmonth === "" || byear === "") {
You can either check this condition before converting to numbers, or change the value you compare to.

Troubleshooting JS Shipping Countdown Timer

Is you'll probably be able to tell I'm a complete JS rookie but I've spent my day working on this code to display a shipping timer, compiled from bits of various other posts on SO (thanks!).
It seemed to be going well until I completed adding all the functionality I needed and now it's not working. When you first run the snippet it works correctly but as soon as it ticks the "day" value displays incorrectly (it should display 'tomorrow' but it switches to 'today') and the timer itself has stopped counting down.
I can't figure out for the life of me where I messed it up so looking for some assistance if possible! Thanks in advance.
JSFiddle: http://jsfiddle.net/c3otusv6/
(function() {
var start = new Date();
start.setHours(14, 0, 0);
var maybePluralize = function maybePluralize(count, noun) {
var suffix = arguments.length <= 2 || arguments[2] === undefined ? 's' : arguments[2];
return count + ' ' + noun + (count !== 1 ? suffix : '');
};
var now = new Date();
var day = now.getDay();
function tick() {
if (day >= 1 && day <= 5 && now < start) {
document.getElementById('ddate').innerHTML = 'today';
} else if (day >= 1 && day <= 4 && now >= start || day == 7) {
document.getElementById('ddate').innerHTML = 'tomorrow';
} else if (day == 5 && now >= start || day == 6) {
document.getElementById('ddate').innerHTML = 'Monday';
}
if (day == 6 || day == 5 && now > start || day == 7 && now < start) {
document.getElementById('countdown').innerHTML = "now";
} else {
if (now > start) { // too late, go to tomorrow
start.setDate(start.getDate() + 1);
}
var remain = (start - now) / 1000;
var hh = Math.floor(remain / 60 / 60 % 60);
var mm = Math.floor(remain / 60 % 60);
document.getElementById('countdown').innerHTML = "in the next <strong>" + maybePluralize(hh, 'hour') + " " + maybePluralize(mm, 'min') + "</strong>";
setTimeout(tick, 1000);
}
}
document.addEventListener('DOMContentLoaded', tick);
})();
If you need to have the function called every second, you need to use setInterval. setTimeout just runs the given function once after the specified number of seconds.
I have made small edit to you fiddle, to make it run every second.
As for the "day" value being incorrect, I think you need to check your if statements. I quite dont understand your business logic.
Also note - Sunday is given by '0' in getDay. And I see you using day == 7, so you might want to check that and do the necessary adjustments. I guess you need to -1 from all your if statements for day.
http://jsfiddle.net/wm9kj8yb/
(function() {
var start = new Date();
var now = new Date();
var day = now.getDay();
start.setHours(14, 0, 0);
function maybePluralize(count, noun) {
var suffix = arguments.length <= 2 || arguments[2] === undefined ? 's' : arguments[2];
return count + ' ' + noun + (count !== 1 ? suffix : '');
};
function tick() {
now = new Date();
day = now.getDay();
if (day >= 1 && day <= 5 && now < start) {
document.getElementById('ddate').innerHTML = 'today';
} else if (day >= 1 && day <= 4 && now >= start || day == 7) {
document.getElementById('ddate').innerHTML = 'tomorrow';
} else if (day == 5 && now >= start || day == 6) {
document.getElementById('ddate').innerHTML = 'Monday';
}
if (day == 6 || day == 5 && now > start || day == 7 && now < start) {
document.getElementById('countdown').innerHTML = "now";
} else {
if (now > start) { // too late, go to tomorrow
start.setDate(start.getDate() + 1);
}
var remain = (start - now) / 1000;
var ss = Math.floor(remain % 60);
remain = Math.floor(remain / 60);
var mm = remain % 60;
remain = Math.floor(remain / 60);
var hh = remain % 60;
document.getElementById('countdown').innerHTML = "in the next <strong>" + maybePluralize(hh, 'hour') + " " + maybePluralize(mm, 'min') + " " + " " + maybePluralize(ss, 'sec') + "</strong>";
}
}
document.addEventListener('DOMContentLoaded', function() {
setInterval(tick, 1000);
});
})();
Order <span id='countdown'></span> for dispatch <span id='ddate'></span>

javascript Date Object how long ago

I'm trying to show how long ago a video was uploaded, i cant seem to get the hours and minutes Date Object Methods to work in this script. I'm working of a script called YouMax 2.0 and i have been editing the function getDateDiff, i have come up with this edit of the function. Thank you for any help on this.
function getDateDiff(timestamp) {
if (null === timestamp || timestamp === "" || timestamp === "undefined") return "?";
var splitDate = ((timestamp.toString().split('T'))[0]).split('-');
var splitTime = ((timestamp.toString().split('T'))[1]).split(':');
var d1 = new Date();
var d1Y = d1.getFullYear();
var d2Y = parseInt(splitDate[0], 10);
var d1M = d1.getMonth() + 1;
var d2M = parseInt(splitDate[1], 10);
var d1D = d1.getDate();
var d2D = parseInt(splitDate[2], 10);
var d1H = d1.getHours();
var d2H = parseInt(splitTime[0], 10);
var d1T = d1.getMinutes();
var d2T = parseInt(splitTime[1], 10);
var diffInMinutes = (d1T + 59 * d1H + 23) - (d2T + 59 * d2H + 23);
if (diffInMinutes <= 1) return "1 Minute";
else if (diffInMinutes <= 59) return diffInMinutes + " Minutes";
var diffInHours = (d1H + 23 * d1M) - (d2H + 23 * d1M);
if (diffInHours <= 1) return "1 Hour";
else if (diffInHours < 23) return diffInHours + " Hours";
var diffInDays = (d1D + 30 * d1M + 12 * d1Y) - (d2D + 30 * d2M + 12 * d2Y);
if (diffInDays < 7) return diffInDays + " days";
else if (diffInDays > 7 && diffInDays < 14) return "1 week";
else if (diffInDays >= 14 && diffInDays < 30) return Math.floor(diffInDays / 7) + " weeks";
var diffInMonths = (d1M + 12 * d1Y) - (d2M + 12 * d2Y);
if (diffInMonths <= 1) return "1 month";
else if (diffInMonths < 12) return diffInMonths + " months";
var diffInYears = Math.floor(diffInMonths / 12);
if (diffInYears <= 1) return "1 year";
else if (diffInYears < 12) return diffInYears + " years";
}
my new function only returns minutes and other and wont update to change of day
I assume you are fetching the timestamp from a mysql database. This was also answered here. The top answer is in php but it is not really different from Javascript. I do suggest using php for this however.
you can see that your splitting was not correct...
this is working fine..
var splitDate = ((timestamp.toString().split('T'))[0]).split('-');
var splitTime = ((timestamp.toString().split('T'))[1]).split(':');
var splitTime1 = ((splitTime[2].toString().split('Z'))[0]).split('.');
splitDate[0] = Year;
splitDate[1] = Month;
splitDate[2] = Day;
splitTime[0] = Hours;
splitTime[1] = Minutes;
splitTime1[0] = Seconds;
splitTime1[1] = MilliSeconds;
you can now perform what ever you want to..

How to add number of days to get the next date from current date without weekends

I want to add some no. of days to get the future date. And weekends should not be included in this. How can I get this?
var startdate = "8-June-2012";
no. of days to add = 10;
enddate should be "22-June-2012"
Try this :
var startDate = "8-June-2012";
startDate = new Date(startDate.replace(/-/g, "/"));
var endDate = "", noOfDaysToAdd = 10, count = 0;
while(count < noOfDaysToAdd){
endDate = new Date(startDate.setDate(startDate.getDate() + 1));
if(endDate.getDay() != 0 && endDate.getDay() != 6){
//Date.getDay() gives weekday starting from 0(Sunday) to 6(Saturday)
count++;
}
}
Here is the demo
function calculateWorkingDayNumbers(startDate, offset)
{
var startDay = startDate.getDay();
if ((startDay % 7) === 1)
{
return ((offset - (offset % 7)) / 7) + ((offset % 7 === 1) ? (1) : (0));
}
else if (offset < 7)
{
if ((startDay === 6))
return 1 + ((offset > 0) ? (1) : (0));
else if (startDay === 0)
return 1 + ((offset === 6) ? (1) : (0));
}
else
{
return calculateWorkingDayNumbers(startDate, (((startDay % 7) + 1) % 7)) + calculateWorkingDayNumbers(startDate.setDate(startDate.getDate() + (((startDay % 7) + 1) % 7)), offset - (((startDay % 7) + 1) % 7));
}
}
This (untested) code is very fast. You could also improve your solution by handling holidays too.

Javascript Relative Time - Display difference in Years & Months

Have been fighting this for too many days. I am trying to display the difference of a date (x) and now as follows:
If the diff is exactly a year or years - just display the year diff
If the diff is years and months (1 year, 5 months) display it like that
If the diff is months (no years), display the months diff
If it's days, display the days.
Hope that's clear - I'm very tired.
Here is my code (the commented lines are what I can't get to work):
function RelativeTime(x){
var plural = '';
var mins = 60, hour = mins * 60; day = hour * 24,
week = day * 7, month = week * 4, year = day * 365;
if (x >= year){ x = (x / year)|0; dformat="year"; }
//else
//if ((x >= year)&& (x >= month)) { x = (x / year), (x / month)|0 ; dformat="year" , "month"; }
else if (x >= month) { x = (x / month)|0; dformat="month"; }
else if (x >= day*4) { x = (x / day)|0; dformat="day"; }
else if (x >= hour) { x = (x / hour)|0; dformat="hr"; }
else if (x >= mins) { x = (x / mins)|0; dformat="min"; }
else { x |= 0; dformat="sec"; }
if (x > 1) plural = 's';
if (x < 0) x = 0;
return x + ' ' + dformat + plural;
}
Try, this http://jsfiddle.net/mk95J/5/:
var age = '';
function RelativeTime(x){
var ymwdhm = [ [31536000, 'year'],
[2419200, 'month'],
[604800, 'week'],
[86400, 'day'],
[3600, 'hour'],
[60, 'min'],
[1, 'sec'] ];
for(var i=0;i<7;i++) {
if(x >= ymwdhm[i][0]) {
var res = parseInt(x / ymwdhm[i][0], 10);
age += res;
age += ymwdhm[i][1];
age += res > 1 ? 's ' : ' '; // plural
RelativeTime(x - (res * ymwdhm[i][0]));
break;
}
}
}
RelativeTime( 35746121 );
document.write(age); // 1year 1month 2weeks 6days 17hours 28mins 41 secs
I would think you would want to construct your string as you go, since you want to build it up. The "else if" constructs would be good if you were only going to show the highest level of difference (only years, or only months).
Maybe something like this:
function RelativeTime(x) {
var mins = 60, hour = mins * 60; day = hour * 24,
week = day * 7, month = week * 4, year = day * 365;
var responseString = '';
if (x >= year) {
var numberOfYears = parseInt(x / year, 10);
x = x - (numberOfYears * year);
responseString += numberOfYears + ' year';
if (numberOfYears > 1) {
responseString += 's';
}
responseString += ' ';
}
if (x >= month) {
var numberOfMonths = parseInt(x / month, 10);
x = x - (numberOfMonths * month);
responseString += numberOfMonths + ' month';
if (numberOfMonths > 1) {
responseString += 's';
}
responseString += ' ';
}
return responseString;
}
// And so on ....
document.write(RelativeTime(35746121));
There are some efficiencies that could be managed within there as well (it's certainly looking like a function could come out of there to replace the almost duplicate code, and you could probably reuse some variables through there).

Categories

Resources