age calculator with javascript - 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.

Related

Computation in javascript using times

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>

subtract dates using jquery date picker

Currently working on jquery clone and datepicker where it will calulate the dates and it will check the overlaping dates. But if the click the less button the code works perfectly it was removing the row but it was not detecting the dates which was there in the cloned div. For example when the user select the date 10-01-1990 & 10-01-1995 for this the total was Total work experience 5 years 0 Months & in the cloned div if the user gave 10-01-1996 & 10-01-2015 so the total was Total work experience 25 years 0 Months. If the user click the lessbtn button the cloned one will remove but the total year was not detecting.
Here is the jquery code
$(document).on('change', ".datepicker", function (){
var valid=true;
$.each($('.datepicker'),function(){
if($(this).val()=="")
{
valid=false;
return false;
}
});
if(valid)
{
var dateStart=[];
var dateEnd=[];
$.each($('.datepicker'),function(){
if($(this).hasClass('startDate'))
dateStart.push($(this).val())
else
dateEnd.push($(this).val())
});
$.each($(dateStart),function(key,value){
var x = dateStart[key].split("-");
var y = dateEnd[key].split("-");
var failed = false;
var fromdate = new Date(x[2], x[0] - 1, x[1]);
var todate = new Date(y[2], y[0] - 1, y[1]);
var locDiffDays = parseInt((todate.getTime() - fromdate.getTime()) / (1000 * 60 * 60 * 24));
console.log(x);
console.log(y);
console.log(fromdate);
console.log(todate);
console.log(locDiffDays);
if(locDiffDays<0){
alert("To date " + dateEnd[key] + " should be greater then from date " + dateStart[key] );
console.log("invalid from and to dates"); failed = true; return false;
}
if(dateStart[key-1]){
var x1 = dateStart[key-1].split("-");
var y1 = dateEnd[key-1].split("-");
var fromdate1 = new Date(x1[2], x1[0] - 1, x1[1]);
var todate1 = new Date(y1[2], y1[0] - 1, y1[1]);
var locDiffDays1 = parseInt((todate1.getTime() - fromdate1.getTime()) / (1000 * 60 * 60 * 24));
console.log(x1);
console.log(y1);
console.log(fromdate1);
console.log(todate1);
console.log(locDiffDays1);
var locDiffDays2 = parseInt((fromdate.getTime() - fromdate1.getTime()) / (1000 * 60 * 60 * 24));
var locDiffDays3 = parseInt((todate.getTime() - todate1.getTime()) / (1000 * 60 * 60 * 24));
var locDiffDays4 = parseInt((fromdate.getTime() - todate1.getTime()) / (1000 * 60 * 60 * 24));
console.log("locDiffDays2: " + locDiffDays2);
if(locDiffDays2<0){
alert("From date " + dateStart[key] + " should be greater than previous from date " + dateStart[key-1] );
console.log("invalid from dates"); failed = true; return false;
}
if(locDiffDays3<0){
alert("To date " + dateStart[key] + " should be greater than previous To date " + dateStart[key-1] );
console.log("invalid from dates"); failed = true; return false;
}
if(locDiffDays4<0){
alert("From date " + dateStart[key] + " should be greater than previous To date " + dateEnd[key-1] );
console.log("invalid from dates"); failed = true; return false;
}
}
if(key == dateStart.length-1 && !failed){
var firstDate = dateStart[0].split('-');
firstDate = new Date(firstDate[2], firstDate[0] - 1, firstDate[1]);
var lastDate = dateEnd[dateEnd.length-1].split('-');
lastDate = new Date(lastDate[2], lastDate[0] - 1, lastDate[1]);
console.log(lastDate);
console.log(firstDate);
//var diffYears = (lastDate.getTime() - firstDate.getTime()) / (1000 * 60 * 60 * 24 * 365);
var diffMonths = monthDiff(firstDate, lastDate);
//diffYears = parseInt(''+diffYears);
var diffYears = diffMonths/12;
diffYears = parseInt(''+diffYears);
diffMonths = diffMonths - (diffYears * 12)
document.getElementById("txt_expy").innerHTML = diffYears + " years";
document.getElementById("txt_expm").innerHTML = diffMonths + " Months";
}
});
Kindly please suggest me.
I am confused here do i want to put any count or something so when the user click the less button the count should reduce one and the value should get detected. Kindly give me tips here
Hereis the fiddle Link
Thanks & Regards
Your issue is you are not calling any logic to update the difference while removing the cloned object. You wrote code for updating the difference only in datepicker.change event.
Demo
Updated code:
$(document).on('change', ".datepicker", function() {
updateDiff()
});
$(document).on('click', ".btn_less1", function() {
var len = $('.cloned-row3').length;
if (len > 1) {
$(this).closest(".btn_less1").parent().parent().parent().remove();
updateDiff();
}
});
function updateDiff() {
var valid = true;
$.each($('.datepicker'), function() {
if ($(this).val() == "") {
valid = false;
return false;
}
});
if (valid) {
var dateStart = [];
var dateEnd = [];
$.each($('.datepicker'), function() {
if ($(this).hasClass('startDate')) dateStart.push($(this).val())
else dateEnd.push($(this).val())
});
$.each($(dateStart), function(key, value) {
var x = dateStart[key].split("-");
var y = dateEnd[key].split("-");
var failed = false;
var fromdate = new Date(x[2], x[0] - 1, x[1]);
var todate = new Date(y[2], y[0] - 1, y[1]);
var locDiffDays = parseInt((todate.getTime() - fromdate.getTime()) / (1000 * 60 * 60 * 24));
if (locDiffDays < 0) {
alert("To date " + dateEnd[key] + " should be greater then from date " + dateStart[key]);
console.log("invalid from and to dates");
failed = true;
return false;
}
if (dateStart[key - 1]) {
var x1 = dateStart[key - 1].split("-");
var y1 = dateEnd[key - 1].split("-");
var fromdate1 = new Date(x1[2], x1[0] - 1, x1[1]);
var todate1 = new Date(y1[2], y1[0] - 1, y1[1]);
var locDiffDays1 = parseInt((todate1.getTime() - fromdate1.getTime()) / (1000 * 60 * 60 * 24));
var locDiffDays2 = parseInt((fromdate.getTime() - fromdate1.getTime()) / (1000 * 60 * 60 * 24));
var locDiffDays3 = parseInt((todate.getTime() - todate1.getTime()) / (1000 * 60 * 60 * 24));
var locDiffDays4 = parseInt((fromdate.getTime() - todate1.getTime()) / (1000 * 60 * 60 * 24));
console.log("locDiffDays2: " + locDiffDays2);
if (locDiffDays2 < 0) {
alert("From date " + dateStart[key] + " should be greater than previous from date " + dateStart[key - 1]);
console.log("invalid from dates");
failed = true;
return false;
}
if (locDiffDays3 < 0) {
alert("To date " + dateStart[key] + " should be greater than previous To date " + dateStart[key - 1]);
console.log("invalid from dates");
failed = true;
return false;
}
if (locDiffDays4 < 0) {
alert("From date " + dateStart[key] + " should be greater than previous To date " + dateEnd[key - 1]);
console.log("invalid from dates");
failed = true;
return false;
}
}
if (key == dateStart.length - 1 && !failed) {
var firstDate = dateStart[0].split('-');
firstDate = new Date(firstDate[2], firstDate[0] - 1, firstDate[1]);
var lastDate = dateEnd[dateEnd.length - 1].split('-');
lastDate = new Date(lastDate[2], lastDate[0] - 1, lastDate[1]);
console.log(lastDate);
console.log(firstDate);
//var diffYears = (lastDate.getTime() - firstDate.getTime()) / (1000 * 60 * 60 * 24 * 365);
var diffMonths = monthDiff(firstDate, lastDate);
//diffYears = parseInt(''+diffYears);
var diffYears = diffMonths / 12;
diffYears = parseInt('' + diffYears);
diffMonths = diffMonths - (diffYears * 12)
document.getElementById("txt_expy").innerHTML = diffYears + " years";
document.getElementById("txt_expm").innerHTML = diffMonths + " Months";
}
});
}
}

replace zero(integer) with space(string) with javascript

I am calculating age from DOB but while i am returning value it show '0' for more see below code
var birth = new Date('DOB');
var curr = new Date();
var age; // this is integer type in database
if(birth != null)
{
var diff = curr - birth;
age= Math.floor(diff / (1000 * 60 * 60 * 24 * 365.25));
} else {
age=' '; // while i return space from here it shows '0' on my output
}
How i can show space insted of '0'
replace it 'null' to null. null it is not string.
var curr = new Date();
var age; // this is integer type in database
if(R2 != null && R2 != undefined )
{
var diff = curr - birth;
AGE= Math.floor(diff / (1000 * 60 * 60 * 24 * 365.25));
}else
AGE=' '; // while i return space from here it shows '0' on my output
}
I did as little modification to your code as I could to not modify it's structure. The main change is to check if age is zero or less than zero, because the original code did return 0 or even negative numbers if the birth date was in the last year or in the future. This should work.
var birth = new Date('DOB');
var curr = new Date();
var age; // this is integer type in database
if (birth != null)
{
var diff = curr - birth;
age = Math.floor(diff / (1000 * 60 * 60 * 24 * 365.25));
if (age < 1) {
age = ' ';
}
} else {
age = ' '; // while i return space from here it shows '0' on my output
}

javascript Date count validation - Last 3 months

I populate 2 dates 03-Mar-2015 and 03-Jun-2015, if Last 3 months option is selected.I perform the below JavaScript validation to check for 90 days. But it shows validation error that the two dates selected are greater than 90 days. But my constraint is not allow users to select more than 3 months duration.
function DtTimeDiff(sender, args) {
var startDate = Date.parse(document.getElementById('ctl00$MainContent$FromYearTxt').value);
var endDate = Date.parse(document.getElementById('ctl00$MainContent$ToYearTxt').value);
var timeDiff = endDate - startDate;
daysDiff = Math.floor(timeDiff / (1000 * 60 * 60 * 24));
if (daysDiff > 90) {
args.IsValid = false;
}
else {
args.IsValid = true;
}
}
How to perform validation for 3 months having 91 days(Mar,Apr,May) and 92 days (Jul,Aug,Sep)? Constrain is not allow users to select more than 3 months duration.
You can add the intermediate code to compute the month duration based on the dates:
function DtTimeDiff() {
var startDate = new Date(document.getElementById('ctl00$MainContent$FromYearTxt').value);
var endDate = new Date(document.getElementById('ctl00$MainContent$ToYearTxt').value);
var monthsDiff = endDate.getMonth() - startDate.getMonth();
var durationLimit = 0;
for (i = 1; i <= monthsDiff; i++) {
durationLimit += new Date(startDate.getFullYear(), startDate.getMonth() + i, 0).getDate();
}
var timeDiff = endDate.getTime() - startDate.getTime();
var daysDiff = Math.floor(timeDiff / (1000 * 60 * 60 * 24));
if (daysDiff > durationLimit) {
args.IsValid = false;
} else {
args.IsValid = true;
}
}
You can try calculate month and date separately
function DtTimeDiff(sender, args) {
startDate = new Date("03-03-2015");/*Assume format is MM-DD-YYYY*/
endDate = new Date("06-01-2015");/*Assume format is MM-DD-YYYY*/
var timeDiff = endDate - startDate;
startDateMonth = startDate.getMonth() + 1;
endDateMonth = endDate.getMonth() + 1;
startDateDate = startDate.getDate();
endDateDdate = endDate.getDate();
if (endDateMonth - startDateMonth >= 3) {
if (endDateDdate - startDateDate >= 0) {
args.IsValid = true;
console.log("In");
} else {
args.IsValid = false;
console.log("Out");
}
}
}

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..

Categories

Resources