Problem with comparing dates in javascript - javascript

HI,
I have the following code that is supposed to compare two dates:
var d = ($('#day').val());
var m = ($('#month').val() -1);
var y = $('#year').val();
var birthdate = new Date(y,m,d);
alert('birthdate is' + birthdate);
var today = new Date();
alert('today is'+ today);
var diff = (today - birthdate);
years = Math.floor(diff/(1000*60*60*24*365));
alert(years);
It's basically working but I'm interested to see if the date of birth makes the user over 18 or not. So I've tried to put in 30th march 1993 - which would make the user 17. I'm alerting out the birthdate and it gives me back the correct date (mon mar 29 1993 00:00:00 GMT + 0100 BST)....however this is evaluating to 18 (alert(years) in the above code) when it should evaluate to seventeen. It's not until I put in 3rd April 1993 that it evaluates to 17.
Any ideas?

You have to mind leap-years, timezones... before reinventing the wheel, I recommend that you use DateJS.
if((18).years().ago().isBefore(birthdate)) {
// handle underage visitors
}

That's because you forgot the leap years.
These years had 366 days and occur usually every four years, so in any 18 years there are about four days more than 365*18, thus moving the neccessary start date four days ahead.
Probably in this case it is easier to check
if ((nowyear - birthyear > 18)
|| ((nowyear - birthyear == 18)&&(nowmonth - birthmonth > 0))
|| ((nowyear - birthyear == 18)&&(nowmonth == birthmonth)&&(nowday - birthday >= 0)))
// you're 18!

If you're looking for age, why not just go the simple route and deal with years, months, and days?
function findAge( birthday ){
var today = new Date();
var age = today.getFullYears() - birthday.getFullYears();
if( today.getMonth() - birthday.getMonth() < 0 ){
age--;
}
else if( today.getDay() - birthday.getDay() < 0 && today.getMonth() == birthday.getMonth() ){
age--;
}
}

try to take a look at this post

Related

date of birth validation if user is above 16

Trying to validate if the user is above 16 but it is failing the condition everytime
here is my code
trying to add a condition to check if user is atleast 16 years old
if (($("#year").val(), month, day)) {
Here is the try
if (($("#year").val(), month, day) <= getAge(new Date())) {
where getAge is a function like this
function getAge(DOB) {
var today = new Date();
var birthDate = new Date(DOB);
var age = today.getFullYear() - birthDate.getFullYear();
var m = today.getMonth() - birthDate.getMonth();
if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
age--;
}
return age;
}
but it is still going into condition if i enter date as 10/22/2001
Your getAge function returns 16 as per your '10/22/2001' example.
But your if statement is strange. You don't need to find out someones birthdate if they were born today.
You can use:
if (getAge($("#year").val()) < 16) {
// the person is 15 or under
}
else {
// the person is 16 or over.
}
Your question and the given code is not that clear. I believe IsDate is a function to check if the input is a valid date, If yes pass that value to getAge function.
if(getAge(**enter your DOB**)>=16){
//write your code if the age is greater than or equal to 16
}

Future Date Calculator

I have the following script that when used, allows the user to see a future date, while excluding weekends. The problem i've encountered though is if the current day is Friday, and i set the future date to 3 days it counts the Saturday and Sunday as working days. I'm really hoping one of you may be able to help as I'm not really that great at Javascript.
The correct example would be: If Today = Friday then 3 working days from now would be Wednesday (not Monday as the script currently calculates it).
Any ideas?
var myDelayInDays = 3;
myDate=new Date();
myDate.setDate(myDate.getDate()+myDelayInDays);
if(myDate.getDay() == 0){//Sunday
myDate.setDate(myDate.getDate() + 2);//Tuesday
} else if(myDate.getDay() == 6){//Saturday
myDate.setDate(myDate.getDate() + 2);//Monday
}
document.write('' + myDate.toLocaleDateString('en-GB'));
Any help would really be great.
Thanks
Try this code by changing date and days to add, A custom loop is used to skip sat and sun
function addDates(startDate,noOfDaysToAdd){
var 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++;
}
}
return startDate;
}
var today = new Date();
var daysToAdd = 3;
alert(addDates(today,daysToAdd));

How to get difference between 2 Dates in Years, Months and days using moment.js

How to get difference between 2 Dates in Years, Months and days using moment.js?
For example the difference between 4/5/2014 & 2/22/2013 should be calculated as 1 Year, 1 Month and 14 Days.
Moment.js can't handle this scenario directly. It does allow you to take the difference between two moments, but the result is an elapsed duration of time in milliseconds. Moment does have a Duration object, but it defines a month as a fixed unit of 30 days - which we know is not always the case.
Fortunately, there is a plugin already created for moment called "Precise Range", which does the right thing. Looking at the source, it does something similar to torazaburo's answer - but it properly accounts for the number of days in the month to adjust.
After including both moment.js and this plugin (readable-range.js) in your project, you can simply call it like this:
var m1 = moment('2/22/2013','M/D/YYYY');
var m2 = moment('4/5/2014','M/D/YYYY');
var diff = moment.preciseDiff(m1, m2);
console.log(diff);
The output is "1 year 1 month 14 days"
You hardly need moment.
d1 = new Date(2014, 3, 5); // April 5, 2014
d2 = new Date(2013, 1, 22); // February 22, 2013
diff = new Date(
d1.getFullYear()-d2.getFullYear(),
d1.getMonth()-d2.getMonth(),
d1.getDate()-d2.getDate()
);
This takes advantage of the fact that the Date constructor is smart about negative values. For instance, if the number of months is negative, it will take that into account and walk back the year.
console.log(diff.getYear(), "Year(s),",
diff.getMonth(), "Month(s), and",
diff.getDate(), "Days.");
>> 1 Year(s), 1 Month(s), and 11 Days.
Your calculation is wrong--it's not 14 days, it's six remaining days in February and the first five days of April, so it's 11 days, as the computer correctly computes.
Second try
This might work better given #MattJohnson's comment:
dy = d1.getYear() - d2.getYear();
dm = d1.getMonth() - d2.getMonth();
dd = d1.getDate() - d2.getDate();
if (dd < 0) { dm -= 1; dd += 30; }
if (dm < 0) { dy -= 1; dm += 12; }
console.log(dy, "Year(s),", dm, "Month(s), and", dd, "Days.");
This worked for me. Verified with Age calculator.
function calculateAge(){
ageText = jQuery("#dob").closest(".form-group").find(".age-text");
ageText.text("");
level2.dob = jQuery("#dob").val();
if(!level2.dob) return;
level2.mdob= moment(level2.dob, 'DD-MM-YYYY');
if(!level2.mdob.isValid()){
alert("Invalid date format");
return;
}
level2.targetDate = moment();//TODO: Fill in the target date
level2.months = level2.targetDate.diff(level2.mdob, 'months'); // Calculate the months
let years = parseInt(level2.months/12); // A year has 12 months irrespective or leap year or not
let balanceMonths = level2.months%12; // The balance gives the number of months
let days;
if(!balanceMonths){ // If no balance months, then the date selected lies in the same month
months = 0; // so months = 0
days = level2.targetDate.diff(level2.mdob, 'days'); // only the days difference
}else{
months = balanceMonths;
dob_date = level2.mdob.date();
target_month = level2.targetDate.month();
construct_date = moment().month(target_month).date(dob_date);
days = level2.targetDate.diff(construct_date, 'days')+1; // There might be one day missed out. Not sure on UTC
}
ageText = years +" years " + months+ " months " + days +" days";
}

Javascript older than 18 on leap years

I'm using this javascript to check if the age entered is older than 18.
function calculateDiffYear(date, month, year)
{
var cur = new Date();
var diff = Math.floor((cur.getTime() - new Date(year, month, date)) / (60 * 60 * 24 * 1000));
diff -= Math.floor((cur.getFullYear() - year) / 4);
return diff / 365;
}
function checkBorn(sender)
{
var root = sender.form;
var date = root.elements['date'].value;
var month = root.elements['month'].value - 1;
var year = root.elements['year'].value;
if (!isValidDate(date, month, year) || calculateDiffYear(date, month, year) < 18) return false;
return true;
}
If works almost right, except for, if we are in a leap year, it gives older than 18 to a person who becomes 18 tomorrow, at least in the tests I'm doing with today date and changing to las year. I tryed adding this but no luck:
if ($('#leap').val()) divider = 366;
else divider = 365;
return diff / divider;
Do you know how can I solve it?
Thank you
If I wanted to test if a particular date was more than 18 years ago I'd do something like this:
function meetsMinimumAge(birthDate, minAge) {
var tempDate = new Date(birthDate.getFullYear() + minAge, birthDate.getMonth(), birthDate.getDate());
return (tempDate <= new Date());
}
if (meetsMinimumAge(new Date(year, month, date), 18)) {
// is OK, do something
} else {
// too young - error
}
Essentially this takes the supplied birthday, adds 18 to it, and checks if that is still on or before today's date.
My age-checking code goes something like this:
function checkAge(dateofbirth) {
var yd, md, dd, now = new Date();
yd = now.getUTCFullYear()-dateofbirth.getUTCFullYear();
md = now.getUTCMonth()-dateofbirth.getUTCMonth();
dd = now.getUTCDate()-dateofbirth.getUTCDate();
if( yd > 18) return true;
if( md > 0) return true;
return dd >= 0;
}
Basically, if the year difference is 19 or more, then they must be over 18.
Otherwise, if the current month is past the month of birth, they are 18 and a few months old.
Otherwise, if the current day is greater than or equal to the day of birth, they are 18 and a few days old (or it is their 18th birthday).
This works regardless of leap years and is much more efficient than your current code.
You can use moment.js to validate it:
var yourDate = year.toString() + "/" + month.toString() + "/" day.toString();
var date = moment(yourDate, "YYYY/MM/DD"); // There are other formats!
var years = moment().diff(date, 'years', false);
if(years >= 18){
return true;
}
return false;

Javascript month difference

How do I calculate difference in months in Javascript?
Please note there are similar questions such as:
What's the best way to calculate date difference in Javascript
But these are based around MS difference, when some months have different number of days than others!
Any easy way to calculate month difference between 2 dates?
Just to be clear, I need to know how many months the dates span, for example:
Jan 29th 2010, and Feb 1st 2010 = 2 months
Jan 1st 2010, and Jan 2nd 2010 = 1 month
Feb 14th 2010, Feb 1st 2011 = 13 months
Feb 1st 2010, March 30th 2011 = 14 months
DisplayTo.getMonth() - DisplayFrom.getMonth() + (12 * (DisplayTo.getFullYear() - DisplayFrom.getFullYear())));
getMonth minus getMonth gives you the month difference between the dates two months.
We then multiply 12 by the number of years difference and add this to the result giving us the full month span.
[edit] Based on comment, I stand corrected. Using the accepted answer I'd use somethng like:
var datefrom = new Date('2001/03/15')
,dateto = new Date('2011/07/21')
,nocando = datefrom<dateto ? null : 'datefrom > dateto!'
,diffM = nocando ||
dateto.getMonth() - datefrom.getMonth()
+ (12 * (dateto.getFullYear() - datefrom.getFullYear()))
,diffY = nocando || Math.floor(diffM/12)
,diffD = dateto.getDate()-datefrom.getDate()
,diffYM = nocando ||
(diffY>0 ? ' Year(s) ' : '')
+ diffM%12+' Month(s) '+(diffD>0? (diffD+' day(s)') : '') ;
console.log(diffYM); //=> 10 Year(s) 4 Month(s) 6 day(s)
I found the following on the website http://ditio.net/2010/05/02/javascript-date-difference-calculation/:
inMonths: function(d1, d2) {
var d1Y = d1.getFullYear();
var d2Y = d2.getFullYear();
var d1M = d1.getMonth();
var d2M = d2.getMonth();
return (d2M+12*d2Y)-(d1M+12*d1Y);
}
In your case, since you want to include all months in the date span, I would just modify the above code by adding 1 to it: return (d2M+12*d2Y)-(d1M+12*d1Y) + 1;
function calcualteMonthYr(){
var fromDate =new Date($('#txtDurationFrom2').val()); // Date picker (text fields)
var toDate = new Date($('#txtDurationTo2').val());
var months=0;
months = (toDate.getFullYear() - fromDate.getFullYear()) * 12;
months -= fromDate.getMonth();
months += toDate.getMonth();
if (toDate.getDate() < fromDate.getDate()){
months--;
}
$('#txtTimePeriod2').val(months); // result
}

Categories