How can I convert this function into Angular directive - javascript

How can I convert this function into an AngularJS directive?
I want to make it validate user input in real time. But even when I'm trying to use it as regular function in controller I'm getting an error:
"Error: pesel.substring is not a function"
function decode(pesel)
{
var year=parseInt(pesel.substring(0,2),10);
var month = parseInt(pesel.substring(2,4),10)-1;
var day = parseInt(pesel.substring(4,6),10);
if(month>80) {
year = year + 1800;
month = month - 80;
}
else if(month > 60) {
year = year + 2200;
month = month - 60;
}
else if (month > 40) {
year = year + 2100;
month = month - 40;
}
else if (month > 20) {
year = year + 2000;
month = month - 20;
}
else {
year += 1900;
}
var birthday=new Date();
birthday.setFullYear(year, month, day);
var weights = [9,7,3,1,9,7,3,1,9,7];
var sum = 0
for(var i=0;i<weights.length;i++) {
sum+=(parseInt(pesel.substring(i,i+1),10) * weights[i]);
}
sum=sum % 10;
var valid=(sum===parseInt(pesel.substring(10,11),10));
//sex
if(parseInt(pesel.substring(9,10),10) % 2 === 1) {
var sex='m';
} else {
var sex='f';
}
return {valid:valid,sex:sex,date:birthday};
}

As Abdo stated above the value you are passing to your function, pesel, probably isn't a string.
The first line in your function should be:
pesel = (pesel || '').toString();
This line makes sure you don't stringify falsey variables and will make sure pesel is in fact a string.

If you want to validate some input, consider as a better option to create a parser/formatter pair or a validator for that purpose.
Use formatter/parsers for retrieving birthday and sex values, and a validator to check the value.
Best

Related

Throw an error when month is not in between 1 -12

So I'm trying to verify a date of bith with the following code and I am having trouble implementing the if statements that check to see if month is greater than 12, it should throw an error and if day is greater than 31 it should also do the same. I would highly appreciate your help.
function isYearCorrect(string) {
let dateOfBirth = new Date((string.substring(0, 2)), (string.substring(2, 4) - 1), (string.substring(4, 6)))
let year = dateOfBirth.getFullYear();
let month = dateOfBirth.getMonth() + 1;
let day = dateOfBirth.getDate();
let isDOBValid = false;
if (month < 10) {
month = "0" + month;
}
/**This statement does not check to see if the month ranges from 1 - 12 but it skips
to the next year and month and leaves the day as is. Basically 971315 becomes 1998-01-15*/
if (month > 12) {
return (`${month} is an invalid month`)
} else {
month;
}
if (day < 10) {
day = "0" + day;
} if (day > 31) {
return (`${day} is an invalid month`);
}else {
day;
}
let fullDate = `${year}-${month}-${day}`;
let dateRegex = /^([12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))$/;
if (dateRegex.test(fullDate) == false) {
isDOBValid;
} else if (dateRegex.test(fullDate) == true) {
isDOBValid = true;
}
return isDOBValid;
}
console.log(isYearCorrect("970812"))
console.log(isYearCorrect("721329"))
You need to put your validation checks conditions before converting the string to the date.
function isYearCorrect(string) {
let yearPiece = +string.substring(0, 2);
let monthPiece = +string.substring(2, 4);
let dayPiece = +string.substring(4, 6);
if (monthPiece > 12) {
return (`${monthPiece} is an invalid month`)
}
if (dayPiece > 31) {
return (`${dayPiece} is an invalid month`);
}
let dateOfBirth = new Date(yearPiece, monthPiece, dayPiece)
let year = dateOfBirth.getFullYear();
let month = dateOfBirth.getMonth() + 1;
let day = dateOfBirth.getDate();
let isDOBValid = false;
/**This statement does not check to see if the month ranges from 1 - 12 but it skips
to the next year and month and leaves the day as is. Basically 971315 becomes 1998-01-15*/
if (month < 10) {
month = "0" + monthPiece;
}
if (day < 10) {
day = "0" + day;
}
let fullDate = `${year}-${month}-${day}`;
let dateRegex = /^([12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))$/;
if (dateRegex.test(fullDate)) {
isDOBValid = true;
}
return isDOBValid;
}
console.log(isYearCorrect("970812"))
console.log(isYearCorrect("721329"))
TLDR: It works as designed.
The solution is to parse the string before putting this into new Date constructor, because what you are trying to do is somehow already done by Date object.
What is happening is that Date is "clever" and it prevents from invalid dates and triggers inner mechanisms, so that when you for example call this function with value "721429" which is supposed to be invalid, you get as a result "1973-3-1". Which is correct (keep in mind February is shorter).
Here you can read more about a date itself and it's acceptable constructors:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date
What is more - I suggest not to use "string" as a name of variable and use const where it's possible (e.g. regex or fullDate variable).

Leap year checker in javascript

I'm trying to put a leap year checker in my Age calculator. It worked for sometime and now it outputs "This is a leap year" every time I select a date. What am I doing wrong?? Thank you!
var year;
function ageCalculator() {
var userinput = document.getElementById("DOB").value;
var dob = new Date(userinput);
if (userinput == null || userinput == '') {
document.getElementById("message").innerHTML = "**Choose a date please!";
return false;
} else {
//calculate month difference from current date in time
var month_diff = Date.now() - dob.getTime();
//convert the calculated difference in date format
var age_dt = new Date(month_diff);
//extract year from date
var year = age_dt.getUTCFullYear();
calYear();
//now calculate the age of the user
var age = Math.abs(year - 1970);
//display the calculated age
return document.getElementById("result").innerHTML =
"Age is: " + age + " years. ";
}
}
function calYear() {
var yr = year;
var yr = document.getElementsByName("year");
if (yr % 400 == 0 || (yr % 100 != 0 && yr % 4 == 0)) {
window.alert("This is not leap!");
} else {
window.alert("This is a leap!");
}
}
<input type="text" id="DOB" />
<button type="button" onclick="ageCalculator()">Calculate</button>
<span id="message"></span><br/>
<span id="result"></span>
document.getElementsByName("year") is a Collection not an Element value! Also, Element.value returns always a string - and it's your task as a developer to convert strings (or know typecasting by heart) to an integer or a float as necessary.
Don't put specifics into a function (like i.e: document.getElementById etc) make it reusable!
Avoid using variables that end up polluting the global Window scope (var year). At some point try to console.log(window.year) and you'll see why.
Don't call a function calYear() ? if it returns a string. Instead call it properly: isLeap() and do what it says! Return a Boolean value.
Only at the point you use/call that function in your UI - decide there the appropriate string you want to show. Don't limit yourself.
Be always careful while using new Date(someUserInput) where someUserInput might be an invalid ISO8601 string. You can easily get false positives.
PS: Date.now() - dob.getTime() cannot by any means be what your comment says: "calculate month difference" that's absolutely not true - Be careful when writing your comments and when naming your functions.
/**
* #param {integer} year
* #return {boolean} - True if year is leap year
*/
const isLeap = (year) => (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
/**
* #param {string} DOBString - A valid ISO8601 dateString
* #return {integer} - Age
*/
const calcAge = (DOBString) => {
const UTC_DOB = new Date(DOBString);
if (!DOBString || isNaN(UTC_DOB)) return;
const UTC_today = new Date();
const m = UTC_today.getUTCMonth() - UTC_DOB.getUTCMonth(); // Month diff
let age = UTC_today.getUTCFullYear() - UTC_DOB.getUTCFullYear();
if (m < 0 || (m === 0 && UTC_today.getUTCDate() < UTC_DOB.getUTCDate())) age--;
return age;
};
// UI/Page/View specific scripts:
const EL_DOB = document.querySelector("#DOB");
const EL_result = document.querySelector("#result");
const EL_leap = document.querySelector("#leap");
const UI_showAgeResult = () => {
const age = calcAge(EL_DOB.value);
const UTC_DOB = new Date(EL_DOB.value);
const is_leap = isLeap(UTC_DOB.getUTCFullYear());
EL_result.textContent = age ? age : "Insert a valid date";
EL_leap.textContent = is_leap ? "Born on a leap year! so cool" : "";
};
// Do it on input Event
EL_DOB.addEventListener("input", UI_showAgeResult);
// And if needed on page init
UI_showAgeResult();
<input id="DOB" type="text" value="2000-02-29"/>
<span id="result"></span><br>
<span id="leap"></span>
Important:
notice that if user Date Of Birth is say "2000-02-29", and say today's date is "2001-02-28" the result age will be arguably-correctly 0.
Only if date is "2001-03-01" will result as 1 y of age.
Kudos:
Slightly modified #naveen answer's code for calculating dates diff → age.
I suggest you look at this version
Calculate age given the birth date in the format YYYYMMDD
To fix YOUR code we need to pass the year to the function and not try to use a non-existing year field
If there was such a field, you could access its value with document.querySelector("[name=year]").value since document.getElementsByName is a collection and the value would be document.getElementsByName("year")[0].value
So what did I do?
passed the DOB year to the leap function
calculated the age from the year of the date difference
I tested with 2000-02-29 and 2001-02-28
NOTE the script ALSO works with 02/29/2016 but not with 29/02/2016 (European format)
var year;
function ageCalculator() {
var userinput = document.getElementById("DOB").value;
var dob = new Date(userinput);
if (isNaN(dob)) {
document.getElementById("message").innerHTML = "**Choose a date please!";
return false;
} else {
//extract year from date
var year = dob.getFullYear();
console.log(year)
testLeap(year);
//calculate difference from current date in milliseconds
var date_diff = Date.now() - dob.getTime();
//convert the calculated difference in date format
var age_dt = new Date(date_diff);
//now calculate the age of the user
var age = Math.abs(1970 - age_dt.getFullYear());
//display the calculated age
return document.getElementById("result").innerHTML =
"Age is: " + age + " years. ";
}
}
function testLeap(yr) {
const isLeap = (yr % 400 == 0 || (yr % 100 != 0 && yr % 4 == 0))
alert(isLeap ? "This is a leap!" : "This is not a leap!");
}
<input type="text" id="DOB" />
<button type="button" onclick="ageCalculator()">Calculate</button>
<span id="message"></span><br/>
<span id="result"></span>
If you only need a function to check if the input year is a leap year or not, you can use Date object:
function isLeapYear(year) {
// year, monthIndex, day
return new Date(year, 1, 29).getFullYear() === year;
}
this is function to check if this year is leap year
function isLeapYear(year){
return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
}
isLeapYear(2000) //true
isLeapYear(2001) // false
EDIT:
so the problem is in document.getElementsByName("year")
i think you should have a HTML named year which is have the year value
<input type="number" name="year" />
Here's another Method I can make sure it will works
function ageCalculator() {
var userinput = document.getElementById("DOB").value;
var dob = new Date(userinput);
if (userinput == null || userinput == '') {
document.getElementById("message").innerHTML = "**Choose a date please!";
return false;
} else {
//calculate month difference from current date in time
var month_diff = Date.now() - dob.getTime();
//convert the calculated difference in date format
var age_dt = new Date(month_diff);
//extract year from date
var year = age_dt.getUTCFullYear();
calYear(year);
//now calculate the age of the user
var age = Math.abs(year - 1970);
//display the calculated age
return document.getElementById("result").innerHTML =
"Age is: " + age + " years. ";
}
}
function calYear(yr) {
if (yr % 400 == 0 || (yr % 100 != 0 && yr % 4 == 0)) {
window.alert("This is not leap!");
} else {
window.alert("This is a leap!");
}
}
Try updating the callYear if condition assuming
yr> 1000 and yr < 8000
function calYear(yr) {
if ((yr % 4 === 0 && yr % 100 !== 0) || yr % 400 === 0 ) {
window.alert("This is not leap!");
} else {
window.alert("This is a leap!");
}
}

how to compare a user entered date to the current date and change a fields background color?

I am new to javascript and am working on a fallible PDF form and trying to set it to do multiple things. The first is I need to compare a user entered date to the current date to see if it is withing 5 years to the day. The second thing I need it to do is to change a fields background color if that date is at the 5 year time or outside of that range. This is the code I have been trying but it hasn't worked so far. There are 37 fields that need to be checked by this.
for(i=1;i<38;i++){
var Y = d.getFullYear();
var d = new Date();
var M = d.getMonth();
var d = new Date();
var D = d.getDay(); //n =2
var strDate = this.getField("Text"+[i]).value;
var arrDate = strDate.split('/');
var month = arrDate[0];
var day = arrDate[1];
var year = arrDate[2];
if(year+5>=Y){
if(M<=month){
if(D<=day){
this.getField("Text[i]").fillColor=color.red;
}}}}
I have updated this, it working now, can you try this now ?
for(i=1;i<38;i++)
{
var todayDate = new Date();
var strDate = "12/25/2009";
var arrDate = strDate.split('/');
var month = arrDate[0];
var day = arrDate[1];
var year = parseInt(arrDate[2]) + 5;
var userEnteredDate = new Date(year, month, day);
if(userEnteredDate <= todayDate)
{
//Color change code here...
}
}
The simplest approach so far as I know, is to instantiate a Date that is five years ago based on current time:
var t = new Date()
t.setFullYear(t.getFullYear() - 5) // t is five years ago
Then you just need to substract the user input date with this one, and see if the result is positive or negative:
var ut = new Date("......") // the Date instance from user input
if(ut - t >= 0) {
// within 5 years
} else {
// more than 5 years ago
}
The reason you can do so, is because when you substract two Date instances one another, they will be internally converted to timestamps. The less a timestamp is, the earlier the time is. So the result of substraction (a number) represents the time in between, in milliseconds.
If you don't care how long in between, you could just compare them:
var ut = new Date("......") // the Date instance from user input
if(ut >= t) {
// within 5 years
} else {
// more than 5 years ago
}
Try this
var d = new Date(),
Y = d.getFullYear(),
M = d.getMonth() + 1, // since this returns 0 - 11
D = d.getDay() + 1, // since this returns 0 - 30
strDate,
arrDate,
month,
day,
year;
for(var i = 1; i < 38; i++) {
strDate = this.getField("Text" + i).value;
arrDate = strDate.split('/');
month = parseInt(arrDate[0], 10);
day = parseInt(arrDate[1], 10);
year = parseInt(arrDate[2], 10);
if (((Y + 5) * 12 + M < year * 12 + month) || ((Y + 5) * 12 + M === year * 12 + month && D < day)) {
this.getField("Text" + i).fillColor = color.red;
}
}

Javascript function , which takes a month/date and disply 12 months/dates back

Is there any javascript function which takes one input parameter (e.g 04/2014 ) and return
12 months and dates with the same format
(e.g 04/2013.........................................04/2014)
i have this one
function calcFullMonth(startDate) {
//copy the date
var dt = new Date(startDate);
dt.setMonth(dt.getMonth() - 1);
return dt;
}
The logic that i have is this .But it gives me only one month back
I need to get 12 months and 1 year back and display them as you see second e.g.
Thanks
Just call your original function as many times as you need, and store them in an array.
function calcFullMonth(startDate, num) {
var months = [];
for (var i = 0; i < num; i++) {
var dt = new Date(startDate);
dt.setMonth(dt.getMonth() + i);
months[i] = dt;
}
return months;
}
For example, to get the current month until this month next year, use num = 13
console.log(calcFullMonth(new Date(), 13));
fiddle
Try the following function
function Get12MonthBack(input) {
var year = input.split("/")[1];
var month = input.split("/")[0];
var d = new Date(year, month);
d.setMonth(d.getMonth()-12);
return (d.getMonth().toString().length == 1 ? "0" + d.getMonth() : d.getMonth()) + "/" + d.getFullYear();
}
Tests
Get12MonthBack("03/2011")
"03/2010"
Get12MonthBack("11/2012")
"11/2012"

How can I calculate the number of years between two dates?

I want to get the number of years between two dates. I can get the number of days between these two days, but if I divide it by 365 the result is incorrect because some years have 366 days.
This is my code to get date difference:
var birthday = value;//format 01/02/1900
var dateParts = birthday.split("/");
var checkindate = new Date(dateParts[2], dateParts[0] - 1, dateParts[1]);
var now = new Date();
var difference = now - checkindate;
var days = difference / (1000*60*60*24);
var thisyear = new Date().getFullYear();
var birthyear = dateParts[2];
var number_of_long_years = 0;
for(var y=birthyear; y <= thisyear; y++){
if( (y % 4 == 0 && y % 100 == 0) || y % 400 == 0 ) {
number_of_long_years++;
}
}
The day count works perfectly. I am trying to do add the additional days when it is a 366-day year, and I'm doing something like this:
var years = ((days)*(thisyear-birthyear))
/((number_of_long_years*366) + ((thisyear-birthyear-number_of_long_years)*365) );
I'm getting the year count. Is this correct, or is there a better way to do this?
Sleek foundation javascript function.
function calculateAge(birthday) { // birthday is a date
var ageDifMs = Date.now() - birthday;
var ageDate = new Date(ageDifMs); // miliseconds from epoch
return Math.abs(ageDate.getUTCFullYear() - 1970);
}
Probably not the answer you're looking for, but at 2.6kb, I would not try to reinvent the wheel and I'd use something like moment.js. Does not have any dependencies.
The diff method is probably what you want: http://momentjs.com/docs/#/displaying/difference/
Using pure javascript Date(), we can calculate the numbers of years like below
document.getElementById('getYearsBtn').addEventListener('click', function () {
var enteredDate = document.getElementById('sampleDate').value;
// Below one is the single line logic to calculate the no. of years...
var years = new Date(new Date() - new Date(enteredDate)).getFullYear() - 1970;
console.log(years);
});
<input type="text" id="sampleDate" value="1980/01/01">
<div>Format: yyyy-mm-dd or yyyy/mm/dd</div><br>
<button id="getYearsBtn">Calculate Years</button>
No for-each loop, no extra jQuery plugin needed... Just call the below function.. Got from Difference between two dates in years
function dateDiffInYears(dateold, datenew) {
var ynew = datenew.getFullYear();
var mnew = datenew.getMonth();
var dnew = datenew.getDate();
var yold = dateold.getFullYear();
var mold = dateold.getMonth();
var dold = dateold.getDate();
var diff = ynew - yold;
if (mold > mnew) diff--;
else {
if (mold == mnew) {
if (dold > dnew) diff--;
}
}
return diff;
}
I use the following for age calculation.
I named it gregorianAge() because this calculation gives exactly how we denote age using Gregorian calendar. i.e. Not counting the end year if month and day is before the month and day of the birth year.
/**
* Calculates human age in years given a birth day. Optionally ageAtDate
* can be provided to calculate age at a specific date
*
* #param string|Date Object birthDate
* #param string|Date Object ageAtDate optional
* #returns integer Age between birthday and a given date or today
*/
gregorianAge = function(birthDate, ageAtDate) {
// convert birthDate to date object if already not
if (Object.prototype.toString.call(birthDate) !== '[object Date]')
birthDate = new Date(birthDate);
// use today's date if ageAtDate is not provided
if (typeof ageAtDate == "undefined")
ageAtDate = new Date();
// convert ageAtDate to date object if already not
else if (Object.prototype.toString.call(ageAtDate) !== '[object Date]')
ageAtDate = new Date(ageAtDate);
// if conversion to date object fails return null
if (ageAtDate == null || birthDate == null)
return null;
var _m = ageAtDate.getMonth() - birthDate.getMonth();
// answer: ageAt year minus birth year less one (1) if month and day of
// ageAt year is before month and day of birth year
return (ageAtDate.getFullYear()) - birthDate.getFullYear()
- ((_m < 0 || (_m === 0 && ageAtDate.getDate() < birthDate.getDate()))?1:0)
}
<input type="text" id="birthDate" value="12 February 1982">
<div style="font-size: small; color: grey">Enter a date in an acceptable format e.g. 10 Dec 2001</div><br>
<button onClick='js:alert(gregorianAge(document.getElementById("birthDate").value))'>What's my age?</button>
Little out of date but here is a function you can use!
function calculateAge(birthMonth, birthDay, birthYear) {
var currentDate = new Date();
var currentYear = currentDate.getFullYear();
var currentMonth = currentDate.getMonth();
var currentDay = currentDate.getDate();
var calculatedAge = currentYear - birthYear;
if (currentMonth < birthMonth - 1) {
calculatedAge--;
}
if (birthMonth - 1 == currentMonth && currentDay < birthDay) {
calculatedAge--;
}
return calculatedAge;
}
var age = calculateAge(12, 8, 1993);
alert(age);
You can get the exact age using timesstamp:
const getAge = (dateOfBirth, dateToCalculate = new Date()) => {
const dob = new Date(dateOfBirth).getTime();
const dateToCompare = new Date(dateToCalculate).getTime();
const age = (dateToCompare - dob) / (365 * 24 * 60 * 60 * 1000);
return Math.floor(age);
};
let currentTime = new Date().getTime();
let birthDateTime= new Date(birthDate).getTime();
let difference = (currentTime - birthDateTime)
var ageInYears=difference/(1000*60*60*24*365)
Yep, moment.js is pretty good for this:
var moment = require('moment');
var startDate = new Date();
var endDate = new Date();
endDate.setDate(endDate.getFullYear() + 5); // Add 5 years to second date
console.log(moment.duration(endDate - startDate).years()); // This should returns 5
getYears(date1, date2) {
let years = new Date(date1).getFullYear() - new Date(date2).getFullYear();
let month = new Date(date1).getMonth() - new Date(date2).getMonth();
let dateDiff = new Date(date1).getDay() - new Date(date2).getDay();
if (dateDiff < 0) {
month -= 1;
}
if (month < 0) {
years -= 1;
}
return years;
}
for(var y=birthyear; y <= thisyear; y++){
if( (y % 4 == 0 && y % 100 == 0) || y % 400 == 0 ) {
days = days-366;
number_of_long_years++;
} else {
days=days-365;
}
year++;
}
can you try this way??
function getYearDiff(startDate, endDate) {
let yearDiff = endDate.getFullYear() - startDate.getFullYear();
if (startDate.getMonth() > endDate.getMonth()) {
yearDiff--;
} else if (startDate.getMonth() === endDate.getMonth()) {
if (startDate.getDate() > endDate.getDate()) {
yearDiff--;
} else if (startDate.getDate() === endDate.getDate()) {
if (startDate.getHours() > endDate.getHours()) {
yearDiff--;
} else if (startDate.getHours() === endDate.getHours()) {
if (startDate.getMinutes() > endDate.getMinutes()) {
yearDiff--;
}
}
}
}
return yearDiff;
}
alert(getYearDiff(firstDate, secondDate));
getAge(month, day, year) {
let yearNow = new Date().getFullYear();
let monthNow = new Date().getMonth() + 1;
let dayNow = new Date().getDate();
if (monthNow === month && dayNow < day || monthNow < month) {
return yearNow - year - 1;
} else {
return yearNow - year;
}
}
If you are using moment
/**
* Convert date of birth into age
* param {string} dateOfBirth - date of birth
* param {string} dateToCalculate - date to compare
* returns {number} - age
*/
function getAge(dateOfBirth, dateToCalculate) {
const dob = moment(dateOfBirth);
return moment(dateToCalculate).diff(dob, 'years');
};
If you want to calculate the years and keep the remainder of the time left for further calculations you can use this function most of the other answers discard the remaining time.
It returns the years and the remainder in milliseconds. This is useful if you want to calculate the time (days or minutes) left after you calculate the years.
The function works by first calculating the difference in years directly using *date.getFullYear()*.
Then it checks if the last year between the two dates is up to a full year by setting the two dates to the same year.
Eg:
oldDate= 1 July 2020,
newDate= 1 June 2022,
years =2020 -2022 =2
Now set old date to new date's year 2022
oldDate = 1 July, 2022
If the last year is not up to a full year then the year is subtracted by 1, the old date is set to the previous year and the interval from the previous year to the current date is calculated to give the remainder in milliseconds.
In the example since old date July 2022 is greater than June 2022 then it means a full year has not yet elapsed (from July 2021 to June 2022) therefore the year count is greater by 1. So years should be decreased by 1. And the actual year count from July 2020 to June 2022 is 1 year ,... months.
If the last year is a full year then the year count by *date.getFullYear()* is correct and the time that has elapsed from the current old date to new date is calculated as the remainder.
If old date= 1 April, 2020, new date = 1 June, 2022 and old date is set to April 2022 after calculating the year =2.
Eg: from April 2020 to June 2022 a duration of 2 years has passed with the remainder being the time from April 2022 to June 2022.
There are also checks for cases where the two dates are in the same year and if the user enters the dates in the wrong order the new Date is less recent than the old Date.
let getYearsAndRemainder = (newDate, oldDate) => {
let remainder = 0;
// get initial years between dates
let years = newDate.getFullYear() - oldDate.getFullYear();
if (years < 0) {// check to make sure the oldDate is the older of the two dates
console.warn('new date is lesser than old date in year difference')
years = 0;
} else {
// set the old date to the same year as new date
oldDate.setFullYear(newDate.getFullYear());
// check if the old date is less than new date in the same year
if (oldDate - newDate > 0) {
//if true, the old date is greater than the new date
// the last but one year between the two dates is not up to a year
if (years != 0) {// dates given in inputs are in the same year, no need to calculate years if the number of years is 0
console.log('Subtracting year');
//set the old year to the previous year
years--;
oldDate.setFullYear(oldDate.getFullYear() - 1);
}
}
}
//calculate the time difference between the old year and newDate.
remainder = newDate - oldDate;
if (remainder < 0) { //check for negative dates due to wrong inputs
console.warn('old date is greater than new Date');
console.log('new date', newDate, 'old date', oldDate);
}
return { years, remainder };
}
let old = new Date('2020-07-01');
console.log( getYearsAndRemainder(new Date(), old));
Date calculation work via the Julian day number. You have to take the first of January of the two years. Then you convert the Gregorian dates into Julian day numbers and after that you take just the difference.
Maybe my function can explain better how to do this in a simple way without loop, calculations and/or libs
function checkYearsDifference(birthDayDate){
var todayDate = new Date();
var thisMonth = todayDate.getMonth();
var thisYear = todayDate.getFullYear();
var thisDay = todayDate.getDate();
var monthBirthday = birthDayDate.getMonth();
var yearBirthday = birthDayDate.getFullYear();
var dayBirthday = birthDayDate.getDate();
//first just make the difference between years
var yearDifference = thisYear - yearBirthday;
//then check months
if (thisMonth == monthBirthday){
//if months are the same then check days
if (thisDay<dayBirthday){
//if today day is before birthday day
//then I have to remove 1 year
//(no birthday yet)
yearDifference = yearDifference -1;
}
//if not no action because year difference is ok
}
else {
if (thisMonth < monthBirthday) {
//if actual month is before birthday one
//then I have to remove 1 year
yearDifference = yearDifference -1;
}
//if not no action because year difference is ok
}
return yearDifference;
}
Bro, moment.js is awesome for this:
The diff method is what you want: http://momentjs.com/docs/#/displaying/difference/
The below function return array of years from the year to the current year.
const getYears = (from = 2017) => {
const diff = moment(new Date()).diff(new Date(`01/01/${from}`), 'years') ;
return [...Array(diff >= 0 ? diff + 1 : 0).keys()].map((num) => {
return from + num;
});
}
console.log(getYears(2016));
<script src="https://momentjs.com/downloads/moment.js"></script>
function dateDiffYearsOnly( dateNew,dateOld) {
function date2ymd(d){ w=new Date(d);return [w.getFullYear(),w.getMonth(),w.getDate()]}
function ymd2N(y){return (((y[0]<<4)+y[1])<<5)+y[2]} // or 60 and 60 // or 13 and 32 // or 25 and 40 //// with ...
function date2N(d){ return ymd2N(date2ymd(d))}
return (date2N(dateNew)-date2N(dateOld))>>9
}
test:
dateDiffYearsOnly(Date.now(),new Date(Date.now()-7*366*24*3600*1000));
dateDiffYearsOnly(Date.now(),new Date(Date.now()-7*365*24*3600*1000))
I went for the following very simple solution. It does not assume you were born in 1970 and it also takes into account the hour of the given birthday date.
function age(birthday) {
let now = new Date();
let year = now.getFullYear();
let years = year - birthday.getFullYear();
birthday = new Date(birthday.getTime()); // clone
birthday.setFullYear(year);
return now >= birthday ? years : years - 1;
}
This one Help you...
$("[id$=btnSubmit]").click(function () {
debugger
var SDate = $("[id$=txtStartDate]").val().split('-');
var Smonth = SDate[0];
var Sday = SDate[1];
var Syear = SDate[2];
// alert(Syear); alert(Sday); alert(Smonth);
var EDate = $("[id$=txtEndDate]").val().split('-');
var Emonth = EDate[0];
var Eday = EDate[1];
var Eyear = EDate[2];
var y = parseInt(Eyear) - parseInt(Syear);
var m, d;
if ((parseInt(Emonth) - parseInt(Smonth)) > 0) {
m = parseInt(Emonth) - parseInt(Smonth);
}
else {
m = parseInt(Emonth) + 12 - parseInt(Smonth);
y = y - 1;
}
if ((parseInt(Eday) - parseInt(Sday)) > 0) {
d = parseInt(Eday) - parseInt(Sday);
}
else {
d = parseInt(Eday) + 30 - parseInt(Sday);
m = m - 1;
}
// alert(y + " " + m + " " + d);
$("[id$=lblAge]").text("your age is " + y + "years " + m + "month " + d + "days");
return false;
});
if someone needs for interest calculation year in float format
function floatYearDiff(olddate, newdate) {
var new_y = newdate.getFullYear();
var old_y = olddate.getFullYear();
var diff_y = new_y - old_y;
var start_year = new Date(olddate);
var end_year = new Date(olddate);
start_year.setFullYear(new_y);
end_year.setFullYear(new_y+1);
if (start_year > newdate) {
start_year.setFullYear(new_y-1);
end_year.setFullYear(new_y);
diff_y--;
}
var diff = diff_y + (newdate - start_year)/(end_year - start_year);
return diff;
}

Categories

Resources