Calculate current age in months - javascript

I need the age in months by a given birthday and the current date:
I found this one, which gives me the age in years:
function getAge(dateString) {
var today = new Date();
var birthDate = new Date(dateString);
var age = today.getFullYear() - birthDate.getFullYear();
var m = today.getMonth() - birthDate.getMonth();
age = age * 12 + m;
return age;
}
But I need the age in months. A five year old child should get the result of 60; if the child is 5 years and 3 months old it should give the result of 63.
http://jsfiddle.net/n33RJ/567/
This doesn't give me the correct value.

Actually, the function you posted does return the number of months.
Copied:
function getAge(dateString) {
var today = new Date();
var birthDate = new Date(dateString);
var age = today.getFullYear() - birthDate.getFullYear();
var m = today.getMonth() - birthDate.getMonth();
age = age * 12 + m;
return age;
}
I ran getAge('1990-May-16') and it returned 305, which is 25 years and 5 months.
Your jsfiddle uses an invalid dateString -- getAge("10.07.14")

Use your year * 12 and then add the month difference. If we have Febuary 2011 but the child is born April 2010, you get 1*12+(-2)=10 Months
function getAge(dateString) {
var today = new Date();
var birthDate = new Date(dateString);
var age = (today.getFullYear() - birthDate.getFullYear())*12+(today.getMonth() - birthDate.getMonth());
return age;
}

function getAge(dateString) {
var today = new Date();
var birth = new Date(dateString);
var years = today.getFullYear() - birth.getFullYear();
var months = today.getMonth() - birth.getMonth();
return years * 12 - months;
}

another using getTime for precision...
function getAge(dateString) {
var today = new Date();
var birth = new Date(dateString);
var timeDiff = today.getTime() - birth.getTime();
var yearDiff = timeDiff / (24 * 60 * 60 * 1000) / 365.25;
return yearDiff * 12;
}

Related

Find out how many days till next birthday and previous birthday - javascript [duplicate]

I tried this but it fails
var diffDays1=(function(){
var oneDay = 24*60*60*1000; // hours*minutes*seconds*milliseconds
var secondDate = new Date(new Date().getFullYear()+1,4,5);
var firstDate = new Date();
return Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));
})();
Wolfram alpha says it's 330 days, diffDays1 shows it's 359. This is probably due to daylight savings or something. Is there a way to accurately calculate days since without doing it server side.
The problem is that you're basing the month on April being 4, when April is 3 in Javascript. See https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date#Parameters
var diffDays1=(function(){
var oneDay = 24*60*60*1000; // hours*minutes*seconds*milliseconds
var secondDate = new Date(new Date().getFullYear()+1,3,5);
var firstDate = new Date();
return Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));
})();
Why reinvent the wheel??
Use datejs
and after:
var startd = Date.parseExact(ind, "yyyy-MM-dd");
var endd = Date.parseExact(end, "yyyy-MM-dd");
var diff = new Date(endd - startd);
var days = diff/1000/60/60/24;
That's all folks!
The moment.js library (http://momentjs.com) handles this and a lot of other JavaScript date issues very easily and nicely. The diff function (http://momentjs.com/docs/#/displaying/difference/) will do exactly what you want.
The fromNow function is also super nice if want to display the number of days from now you could do something like:
moment([2014, 4, 5]).fromNow();
would produce something like "330 days" if it's 330 days away.
http://momentjs.com/docs/#/displaying/fromnow/
Here's a cleaner solution using moment, which handles all cases correctly (including today, upcoming birthday this year or not until next year, time zone, leap year, etc.):
const birthdate = '2018-12-15';
const today = moment().format('YYYY-MM-DD');
const years = moment().diff(birthdate, 'years');
const adjustToday = birthdate.substring(5) === today.substring(5) ? 0 : 1;
const nextBirthday = moment(birthdate).add(years + adjustToday, 'years');
const daysUntilBirthday = nextBirthday.diff(today, 'days');
Simple, fast, accurate!
Here's the same code, explained:
// This is the birthdate we're checking, in ISO 8601 format
const birthdate = '2018-12-15';
// Get today's date in ISO 8601 format
const today = moment().format('YYYY-MM-DD');
// Calculate current age of person in years (moment truncates by default)
const years = moment().diff(birthdate, 'years');
// Special case if birthday is today; we do NOT need an extra year added
const adjustToday = birthdate.substring(5) === today.substring(5) ? 0 : 1;
// Add age plus one year (unless birthday is today) to get next birthday
const nextBirthday = moment(birthdate).add(years + adjustToday, 'years');
// Final calculation in days
const daysUntilBirthday = nextBirthday.diff(today, 'days');
If the birthday is today, the result will be 0; if it is tomorrow, the result will be 1, and so on.
The selected solution doesn't work if the birthday is this year, because it sums 1 to getFullYear.
This is my solution, it also prevents two edge cases: birthday today and 1 day remaining.
const birthdayDay = 19;
const birthdayMonth = 11; // december === 11
const myBirthdayThisYear = new Date(new Date().getFullYear(), 11, 19).setHours(23, 59, 59);
export const daysUntilBirthday = () => {
const addToYear = myBirthdayThisYear > Date.now() ? 0 : 1;
const oneDay = 24 * 60 * 60 * 1000;
const secondDate = new Date(new Date().getFullYear() + addToYear, birthdayMonth, birthdayDay);
const firstDate = new Date();
const days = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime()) / (oneDay)));
const daysOrDay = days === 1 ? 'day' : 'days';
return days !== 365 ? `${days} ${daysOrDay} until my birthday 😉😉` : '🎂 TODAY IS MY BIRTHDAY 🎂';
};

javascript calculate days lived from birthday

Im trying to make a script which calculate the days you live. My idea is the user to select their birthday by clicking buttons. I read some scripts and wrote some questions and finally a good guy sent me this code, but it isn working for me.. JSFIDDLE
function IncrementDay(month,year)
{
var lastDay = new Date(year, month, 0).getDate();
var nDay=document.getElementById("bday").value;
++nDay;
if (nDay > lastDay) {
nDay =1;
}
document.getElementById("bday").value=nDay;
}
function IncrementMonth(from_IncrementDay = false)
{
var nMonth = document.getElementById("bmonth").value;
++nMonth;
if (nMonth==13) {
nMonth =1;
}
document.getElementById("bmonth").value=nMonth;
}
function isValidDate(s) {
var bits = s.split('/');
var y = bits[0], m = bits[1], d = bits[2];
// Assume not leap year by default (note zero index for Jan)
var daysInMonth = [31,28,31,30,31,30,31,31,30,31,30,31];
// If evenly divisible by 4 and not evenly divisible by 100,
// or is evenly divisible by 400, then a leap year
if ( (!(y % 4) && y % 100) || !(y % 400)) {
daysInMonth[1] = 29;
}
return d <= daysInMonth[--m]
}
function days_between(date1, date2) {
// The number of milliseconds in one day
var ONE_DAY = 1000 * 60 * 60 * 24
// Convert both dates to milliseconds
var date1_ms = date1.getTime()
var date2_ms = date2.getTime()
// Calculate the difference in milliseconds
var difference_ms = Math.abs(date1_ms - date2_ms)
// Convert back to days and return
return Math.round(difference_ms/ONE_DAY)
}
function calculate() {
var _bd = document.getElementById('byear').value + "/" + document.getElementById('bmonth').value + "/" + document.getElementById('bday').value;
if (!isValidDate(_bd)) return;
var _days = days_between(new Date(), new Date(_bd));
document.getElementById("days").innerHTML = _days;
}
var cDate= new Date();
var cDay = cDate.getDate();
var cMonth = cDate.getMonth();
var cYear = cDate.getFullYear();
var days_gone = 0;
++cMonth;
document.getElementById("bday").value=cDay;
document.getElementById("bmonth").value=cMonth;
document.getElementById("byear").value=cYear;
Im not very familiar with javascript, can you tell me where's the mistake? thanks.
var oneDay = 24*60*60*1000; // hours*minutes*seconds*milliseconds
var firstDate = new Date(2008,01,12);
var secondDate = new Date();
var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));
I like the moment js library for this.
http://momentjs.com/
This is how you would do it with moment.js
var today = moment();
var birthDate = moment([2000, 12, 31]); // 2000 (year), 12 (month), 31 (day)
var daysDiff = today.diff(birthDate, 'days'); //4823
if you want the difference in years
var yearsDiff = today.diff(birthDate, 'years'); //13

javascript age calculator keep giving wrong numbers,

i am trying to do a javascript program and calculate the age for the use, i have done the code below,
function submitForm() {
var d = new Date();
var year = d.getFullYear();
var month = d.getMonth();
var days = d.getDay();
var minutes = d.getMinutes();
var hours = d.getHours();
var byear = document.dataform.year.selectedIndex;
var bmonth = document.dataform.month.selectedIndex;
var bday = document.dataform.day.selectedIndex;
var bhours = bday * 24;
var bmin = 60 * b hours;
var dyears = year - byear;
var dmonth = month - bmonth;
var ddays = (days - bday);
var dhours = hours - bhours;
var dminutes = minutes - bmin;
var daysTillBDay = 365 - bday;
if (isLeapYear() == true) {
dyears = year - byear;
dmonth = month - bmonth;
ddays = (days - bday) + 1;
dhours = hours - bhours;
dminutes = minutes - bmin;
daysTillBDay = 365 - bday;
}
var el = document.getElementsByName('uyears');
el[0].value = dyears + " years old.";
el = document.getElementsByName('umonths');
el[0].value = dmonth + " months old.";
document.getElementsByName('udays')[0].value = ddays;
document.getElementsByName('lmonths')[0].value = dmonth;
document.getElementsByName('ldays')[0].value = ddays;
document.getElementsByName('lhrs')[0].value = dhours;
document.getElementsByName('lmin')[0].value = dminutes;
document.getElementsByName('bdays')[0].value = daysTillBDay + " days left till your birthday.";
}
I think i will be work before i try to run the program, after i run the program, i found that the program give me almost everthing wrong, i have the year like 2013(newest yrs.), and the month i will equal the negativetive number such as -1 if i enter 11. I just try to find users age, which i believe is the date of today(today's gate)-(the birthday date), but is not workng now, anyobne know what>?
The problem is very simple (and one mistake that I've made myself) - new Date().getDay() returns the day in the week (0 for Monday, through to 6 for Sunday), not the day in the month.
The function that you're looking for is new Date().getDate(), which returns 1 for January the 1st, 25 on Christmas Day, and so on.

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;
}

How to calculate date difference in JavaScript? [duplicate]

This question already has answers here:
How to calculate number of days between two dates?
(42 answers)
Closed 3 months ago.
I want to calculate date difference in days, hours, minutes, seconds, milliseconds, nanoseconds. How can I do it?
Assuming you have two Date objects, you can just subtract them to get the difference in milliseconds:
var difference = date2 - date1;
From there, you can use simple arithmetic to derive the other values.
var DateDiff = {
inDays: function(d1, d2) {
var t2 = d2.getTime();
var t1 = d1.getTime();
return Math.floor((t2-t1)/(24*3600*1000));
},
inWeeks: function(d1, d2) {
var t2 = d2.getTime();
var t1 = d1.getTime();
return parseInt((t2-t1)/(24*3600*1000*7));
},
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);
},
inYears: function(d1, d2) {
return d2.getFullYear()-d1.getFullYear();
}
}
var dString = "May, 20, 1984";
var d1 = new Date(dString);
var d2 = new Date();
document.write("<br />Number of <b>days</b> since "+dString+": "+DateDiff.inDays(d1, d2));
document.write("<br />Number of <b>weeks</b> since "+dString+": "+DateDiff.inWeeks(d1, d2));
document.write("<br />Number of <b>months</b> since "+dString+": "+DateDiff.inMonths(d1, d2));
document.write("<br />Number of <b>years</b> since "+dString+": "+DateDiff.inYears(d1, d2));
Code sample taken from here.
Another solution is convert difference to a new Date object and get that date's year(diff from 1970), month, day etc.
var date1 = new Date(2010, 6, 17);
var date2 = new Date(2013, 12, 18);
var diff = new Date(date2.getTime() - date1.getTime());
// diff is: Thu Jul 05 1973 04:00:00 GMT+0300 (EEST)
console.log(diff.getUTCFullYear() - 1970); // Gives difference as year
// 3
console.log(diff.getUTCMonth()); // Gives month count of difference
// 6
console.log(diff.getUTCDate() - 1); // Gives day count of difference
// 4
So difference is like "3 years and 6 months and 4 days". If you want to take difference in a human readable style, that can help you.
Expressions like "difference in days" are never as simple as they seem. If you have the following dates:
d1: 2011-10-15 23:59:00
d1: 2011-10-16 00:01:00
the difference in time is 2 minutes, should the "difference in days" be 1 or 0? Similar issues arise for any expression of the difference in months, years or whatever since years, months and days are of different lengths and different times (e.g. the day that daylight saving starts is 1 hour shorter than usual and two hours shorter than the day that it ends).
Here is a function for a difference in days that ignores the time, i.e. for the above dates it returns 1.
/*
Get the number of days between two dates - not inclusive.
"between" does not include the start date, so days
between Thursday and Friday is one, Thursday to Saturday
is two, and so on. Between Friday and the following Friday is 7.
e.g. getDaysBetweenDates( 22-Jul-2011, 29-jul-2011) => 7.
If want inclusive dates (e.g. leave from 1/1/2011 to 30/1/2011),
use date prior to start date (i.e. 31/12/2010 to 30/1/2011).
Only calculates whole days.
Assumes d0 <= d1
*/
function getDaysBetweenDates(d0, d1) {
var msPerDay = 8.64e7;
// Copy dates so don't mess them up
var x0 = new Date(d0);
var x1 = new Date(d1);
// Set to noon - avoid DST errors
x0.setHours(12,0,0);
x1.setHours(12,0,0);
// Round to remove daylight saving errors
return Math.round( (x1 - x0) / msPerDay );
}
This can be more concise:
/* Return number of days between d0 and d1.
** Returns positive if d0 < d1, otherwise negative.
**
** e.g. between 2000-02-28 and 2001-02-28 there are 366 days
** between 2015-12-28 and 2015-12-29 there is 1 day
** between 2015-12-28 23:59:59 and 2015-12-29 00:00:01 there is 1 day
** between 2015-12-28 00:00:01 and 2015-12-28 23:59:59 there are 0 days
**
** #param {Date} d0 - start date
** #param {Date} d1 - end date
** #returns {number} - whole number of days between d0 and d1
**
*/
function daysDifference(d0, d1) {
var diff = new Date(+d1).setHours(12) - new Date(+d0).setHours(12);
return Math.round(diff/8.64e7);
}
// Simple formatter
function formatDate(date){
return [date.getFullYear(),('0'+(date.getMonth()+1)).slice(-2),('0'+date.getDate()).slice(-2)].join('-');
}
// Examples
[[new Date(2000,1,28), new Date(2001,1,28)], // Leap year
[new Date(2001,1,28), new Date(2002,1,28)], // Not leap year
[new Date(2017,0,1), new Date(2017,1,1)]
].forEach(function(dates) {
document.write('From ' + formatDate(dates[0]) + ' to ' + formatDate(dates[1]) +
' is ' + daysDifference(dates[0],dates[1]) + ' days<br>');
});
<html lang="en">
<head>
<script>
function getDateDiff(time1, time2) {
var str1= time1.split('/');
var str2= time2.split('/');
// yyyy , mm , dd
var t1 = new Date(str1[2], str1[0]-1, str1[1]);
var t2 = new Date(str2[2], str2[0]-1, str2[1]);
var diffMS = t1 - t2;
console.log(diffMS + ' ms');
var diffS = diffMS / 1000;
console.log(diffS + ' ');
var diffM = diffS / 60;
console.log(diffM + ' minutes');
var diffH = diffM / 60;
console.log(diffH + ' hours');
var diffD = diffH / 24;
console.log(diffD + ' days');
alert(diffD);
}
//alert(getDateDiff('10/18/2013','10/14/2013'));
</script>
</head>
<body>
<input type="button"
onclick="getDateDiff('10/18/2013','10/14/2013')"
value="clickHere()" />
</body>
</html>
use Moment.js for all your JavaScript related date-time calculation
Answer to your question is:
var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
a.diff(b) // 86400000
Complete details can be found here
adding to #paresh mayani 's answer, to work like Facebook - showing how much time has passed in sec/min/hours/weeks/months/years
var DateDiff = {
inSeconds: function(d1, d2) {
var t2 = d2.getTime();
var t1 = d1.getTime();
return parseInt((t2-t1)/1000);
},
inMinutes: function(d1, d2) {
var t2 = d2.getTime();
var t1 = d1.getTime();
return parseInt((t2-t1)/60000);
},
inHours: function(d1, d2) {
var t2 = d2.getTime();
var t1 = d1.getTime();
return parseInt((t2-t1)/3600000);
},
inDays: function(d1, d2) {
var t2 = d2.getTime();
var t1 = d1.getTime();
return parseInt((t2-t1)/(24*3600*1000));
},
inWeeks: function(d1, d2) {
var t2 = d2.getTime();
var t1 = d1.getTime();
return parseInt((t2-t1)/(24*3600*1000*7));
},
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);
},
inYears: function(d1, d2) {
return d2.getFullYear()-d1.getFullYear();
}
}
var dString = "May, 20, 1984"; //will also get (Y-m-d H:i:s)
var d1 = new Date(dString);
var d2 = new Date();
var timeLaps = DateDiff.inSeconds(d1, d2);
var dateOutput = "";
if (timeLaps<60)
{
dateOutput = timeLaps+" seconds";
}
else
{
timeLaps = DateDiff.inMinutes(d1, d2);
if (timeLaps<60)
{
dateOutput = timeLaps+" minutes";
}
else
{
timeLaps = DateDiff.inHours(d1, d2);
if (timeLaps<24)
{
dateOutput = timeLaps+" hours";
}
else
{
timeLaps = DateDiff.inDays(d1, d2);
if (timeLaps<7)
{
dateOutput = timeLaps+" days";
}
else
{
timeLaps = DateDiff.inWeeks(d1, d2);
if (timeLaps<4)
{
dateOutput = timeLaps+" weeks";
}
else
{
timeLaps = DateDiff.inMonths(d1, d2);
if (timeLaps<12)
{
dateOutput = timeLaps+" months";
}
else
{
timeLaps = DateDiff.inYears(d1, d2);
dateOutput = timeLaps+" years";
}
}
}
}
}
}
alert (dateOutput);
With momentjs it's simple:
moment("2016-04-08").fromNow();
function DateDiff(date1, date2) {
date1.setHours(0);
date1.setMinutes(0, 0, 0);
date2.setHours(0);
date2.setMinutes(0, 0, 0);
var datediff = Math.abs(date1.getTime() - date2.getTime()); // difference
return parseInt(datediff / (24 * 60 * 60 * 1000), 10); //Convert values days and return value
}
var d1=new Date(2011,0,1); // jan,1 2011
var d2=new Date(); // now
var diff=d2-d1,sign=diff<0?-1:1,milliseconds,seconds,minutes,hours,days;
diff/=sign; // or diff=Math.abs(diff);
diff=(diff-(milliseconds=diff%1000))/1000;
diff=(diff-(seconds=diff%60))/60;
diff=(diff-(minutes=diff%60))/60;
days=(diff-(hours=diff%24))/24;
console.info(sign===1?"Elapsed: ":"Remains: ",
days+" days, ",
hours+" hours, ",
minutes+" minutes, ",
seconds+" seconds, ",
milliseconds+" milliseconds.");
I think this should do it.
let today = new Date();
let form_date=new Date('2019-10-23')
let difference=form_date>today ? form_date-today : today-form_date
let diff_days=Math.floor(difference/(1000*3600*24))
based on javascript runtime prototype implementation you can use simple arithmetic to subtract dates as in bellow
var sep = new Date(2020, 07, 31, 23, 59, 59);
var today = new Date();
var diffD = Math.floor((sep - today) / (1000 * 60 * 60 * 24));
console.log('Day Diff: '+diffD);
the difference return answer as milliseconds, then you have to convert it by division:
by 1000 to convert to second
by 1000×60 convert to minute
by 1000×60×60 convert to hour
by 1000×60×60×24 convert to day
function DateDiff(b, e)
{
let
endYear = e.getFullYear(),
endMonth = e.getMonth(),
years = endYear - b.getFullYear(),
months = endMonth - b.getMonth(),
days = e.getDate() - b.getDate();
if (months < 0)
{
years--;
months += 12;
}
if (days < 0)
{
months--;
days += new Date(endYear, endMonth, 0).getDate();
}
return [years, months, days];
}
[years, months, days] = DateDiff(
new Date("October 21, 1980"),
new Date("July 11, 2017")); // 36 8 20
Sorry but flat millisecond calculation is not reliable
Thanks for all the responses, but few of the functions I tried are failing either on
1. A date near today's date
2. A date in 1970 or
3. A date in a leap year.
Approach that best worked for me and covers all scenario e.g. leap year, near date in 1970, feb 29 etc.
var someday = new Date("8/1/1985");
var today = new Date();
var years = today.getFullYear() - someday.getFullYear();
// Reset someday to the current year.
someday.setFullYear(today.getFullYear());
// Depending on when that day falls for this year, subtract 1.
if (today < someday)
{
years--;
}
document.write("Its been " + years + " full years.");
This code will return the difference between two dates in days:
const previous_date = new Date("2019-12-23");
const current_date = new Date();
const current_year = current_date.getFullYear();
const previous_date_year =
previous_date.getFullYear();
const difference_in_years = current_year -
previous_date_year;
let months = current_date.getMonth();
months = months + 1; // for making the indexing
// of months from 1
for(let i = 0; i < difference_in_years; i++){
months = months + 12;
}
let days = current_date.getDate();
days = days + (months * 30.417);
console.log(`The days between ${current_date} and
${previous_date} are : ${days} (approximately)`);
If you are using moment.js then it is pretty simple to find date difference.
var now = "04/09/2013 15:00:00";
var then = "04/09/2013 14:20:30";
moment.utc(moment(now,"DD/MM/YYYY HH:mm:ss").diff(moment(then,"DD/MM/YYYY HH:mm:ss"))).format("HH:mm:ss")
This is how you can implement difference between dates without a framework.
function getDateDiff(dateOne, dateTwo) {
if(dateOne.charAt(2)=='-' & dateTwo.charAt(2)=='-'){
dateOne = new Date(formatDate(dateOne));
dateTwo = new Date(formatDate(dateTwo));
}
else{
dateOne = new Date(dateOne);
dateTwo = new Date(dateTwo);
}
let timeDiff = Math.abs(dateOne.getTime() - dateTwo.getTime());
let diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
let diffMonths = Math.ceil(diffDays/31);
let diffYears = Math.ceil(diffMonths/12);
let message = "Difference in Days: " + diffDays + " " +
"Difference in Months: " + diffMonths+ " " +
"Difference in Years: " + diffYears;
return message;
}
function formatDate(date) {
return date.split('-').reverse().join('-');
}
console.log(getDateDiff("23-04-2017", "23-04-2018"));
function daysInMonth (month, year) {
return new Date(year, month, 0).getDate();
}
function getduration(){
let A= document.getElementById("date1_id").value
let B= document.getElementById("date2_id").value
let C=Number(A.substring(3,5))
let D=Number(B.substring(3,5))
let dif=D-C
let arr=[];
let sum=0;
for (let i=0;i<dif+1;i++){
sum+=Number(daysInMonth(i+C,2019))
}
let sum_alter=0;
for (let i=0;i<dif;i++){
sum_alter+=Number(daysInMonth(i+C,2019))
}
let no_of_month=(Number(B.substring(3,5)) - Number(A.substring(3,5)))
let days=[];
if ((Number(B.substring(3,5)) - Number(A.substring(3,5)))>0||Number(B.substring(0,2)) - Number(A.substring(0,2))<0){
days=Number(B.substring(0,2)) - Number(A.substring(0,2)) + sum_alter
}
if ((Number(B.substring(3,5)) == Number(A.substring(3,5)))){
console.log(Number(B.substring(0,2)) - Number(A.substring(0,2)) + sum_alter)
}
time_1=[]; time_2=[]; let hour=[];
time_1=document.getElementById("time1_id").value
time_2=document.getElementById("time2_id").value
if (time_1.substring(0,2)=="12"){
time_1="00:00:00 PM"
}
if (time_1.substring(9,11)==time_2.substring(9,11)){
hour=Math.abs(Number(time_2.substring(0,2)) - Number(time_1.substring(0,2)))
}
if (time_1.substring(9,11)!=time_2.substring(9,11)){
hour=Math.abs(Number(time_2.substring(0,2)) - Number(time_1.substring(0,2)))+12
}
let min=Math.abs(Number(time_1.substring(3,5))-Number(time_2.substring(3,5)))
document.getElementById("duration_id").value=days +" days "+ hour+" hour " + min+" min "
}
<input type="text" id="date1_id" placeholder="28/05/2019">
<input type="text" id="date2_id" placeholder="29/06/2019">
<br><br>
<input type="text" id="time1_id" placeholder="08:01:00 AM">
<input type="text" id="time2_id" placeholder="00:00:00 PM">
<br><br>
<button class="text" onClick="getduration()">Submit </button>
<br><br>
<input type="text" id="duration_id" placeholder="days hour min">
var date1 = new Date("06/30/2019");
var date2 = new Date("07/30/2019");
// To calculate the time difference of two dates
var Difference_In_Time = date2.getTime() - date1.getTime();
// To calculate the no. of days between two dates
var Difference_In_Days = Difference_In_Time / (1000 * 3600 * 24);
//To display the final no. of days (result)
document.write("Total number of days between dates <br>"
+ date1 + "<br> and <br>"
+ date2 + " is: <br> "
+ Difference_In_Days);
this should work just fine if you just need to show what time left, since JavaScript uses frames for its time you'll have get your End Time - The Time RN after that we can divide it by 1000 since apparently 1000 frames = 1 seconds, after that you can use the basic math of time, but there's still a problem to this code, since the calculation is static, it can't compensate for the different day total in a year (360/365/366), the bunch of IF after the calculation is to make it null if the time is lower than 0, hope this helps even though it's not exactly what you're asking :)
var now = new Date();
var end = new Date("End Time");
var total = (end - now) ;
var totalD = Math.abs(Math.floor(total/1000));
var years = Math.floor(totalD / (365*60*60*24));
var months = Math.floor((totalD - years*365*60*60*24) / (30*60*60*24));
var days = Math.floor((totalD - years*365*60*60*24 - months*30*60*60*24)/ (60*60*24));
var hours = Math.floor((totalD - years*365*60*60*24 - months*30*60*60*24 - days*60*60*24)/ (60*60));
var minutes = Math.floor((totalD - years*365*60*60*24 - months*30*60*60*24 - days*60*60*24 - hours*60*60)/ (60));
var seconds = Math.floor(totalD - years*365*60*60*24 - months*30*60*60*24 - days*60*60*24 - hours*60*60 - minutes*60);
var Y = years < 1 ? "" : years + " Years ";
var M = months < 1 ? "" : months + " Months ";
var D = days < 1 ? "" : days + " Days ";
var H = hours < 1 ? "" : hours + " Hours ";
var I = minutes < 1 ? "" : minutes + " Minutes ";
var S = seconds < 1 ? "" : seconds + " Seconds ";
var A = years == 0 && months == 0 && days == 0 && hours == 0 && minutes == 0 && seconds == 0 ? "Sending" : " Remaining";
document.getElementById('txt').innerHTML = Y + M + D + H + I + S + A;
Ok, there are a bunch of ways you can do that.
Yes, you can use plain old JS. Just try:
let dt1 = new Date()
let dt2 = new Date()
Let's emulate passage using Date.prototype.setMinutes and make sure we are in range.
dt1.setMinutes(7)
dt2.setMinutes(42)
console.log('Elapsed seconds:',(dt2-dt1)/1000)
Alternatively you could use some library like js-joda, where you can easily do things like this (directly from docs):
var dt1 = LocalDateTime.parse("2016-02-26T23:55:42.123");
var dt2 = dt1
.plusYears(6)
.plusMonths(12)
.plusHours(2)
.plusMinutes(42)
.plusSeconds(12);
// obtain the duration between the two dates
dt1.until(dt2, ChronoUnit.YEARS); // 7
dt1.until(dt2, ChronoUnit.MONTHS); // 84
dt1.until(dt2, ChronoUnit.WEEKS); // 356
dt1.until(dt2, ChronoUnit.DAYS); // 2557
dt1.until(dt2, ChronoUnit.HOURS); // 61370
dt1.until(dt2, ChronoUnit.MINUTES); // 3682242
dt1.until(dt2, ChronoUnit.SECONDS); // 220934532
There are plenty more libraries ofc, but js-joda has an added bonus of being available also in Java, where it has been extensively tested. All those tests have been migrated to js-joda, it's also immutable.
I made a below function to get the difference between now and "2021-02-26T21:50:42.123".
The difference return answer as milliseconds, so I convert it by using this formula:
(1000 * 3600 * 24).
function getDiff(dateAcquired) {
let calDiff = Math.floor(
(new Date() - new Date(dateAcquired)) / (1000 * 3600 * 24)
);
return calDiff;
}
console.log(getDiff("2021-02-26T21:50:42.123"));
Can be useful :
const date_diff = (date1, date2) => Math.ceil(Math.abs(date1 - date2)/24 * 60 * 60 * 1000)
or
const date_diff = (date1, date2) => Math.ceil(Math.abs(date1 - date2)/86400000)
where 24 * 60 * 60 * 1000 is (day * minutes * seconds * milliseconds) = 86400000 milliseconds in one day
Thank you
// the idea is to get time left for new year.
// Not considering milliseconds as of now, but that
// can be done
var newYear = '1 Jan 2023';
const secondsInAMin = 60;
const secondsInAnHour = 60 * secondsInAMin;
const secondsInADay = 24 * secondsInAnHour;
function DateDiffJs() {
var newYearDate = new Date(newYear);
var currDate = new Date();
var remainingSecondsInDateDiff = (newYearDate - currDate) / 1000;
var days = Math.floor(remainingSecondsInDateDiff / secondsInADay);
var remainingSecondsAfterDays = remainingSecondsInDateDiff - (days * secondsInADay);
var hours = Math.floor(remainingSecondsAfterDays / secondsInAnHour);
var remainingSecondsAfterhours = remainingSecondsAfterDays - (hours * secondsInAnHour);
var mins = Math.floor(remainingSecondsAfterhours / secondsInAMin);
var seconds = Math.floor(remainingSecondsAfterhours - (mins * secondsInAMin));
console.log(`days :: ${days}`)
console.log(`hours :: ${hours}`)
console.log(`mins :: ${mins}`)
console.log(`seconds :: ${seconds}`)
}
DateDiffJs();

Categories

Resources