JavaScript calculate years and days from start date - javascript

I have date when someone is born, and I need to calculate with JavaScript or jQuery or so, how many years, days since birth date, until now.
So result can be like 20 years, 89 days.
I need to have same results as Wikipedia does with their function of "age in years", as it takes leap years in account and what not. So far I got code that works, but in some cases makes mistake of 1 day. My function is:
function DateDiff(date1, date2){
var res=((date1.getTime() - date2.getTime())/1000/60/60/24)-offset_d;
var full_days=Math.floor(res/365.25);
var f1=Math.round((res%365.25))
return full_days + " years, " +f1 + " days" ; }
Thanks for your help, I am doing this for days.

I wrote the following a while back, you should be able to tweak it to do the job:
// Given a date object, calcualte the number of
// days in the month
function daysInMonth(x) {
var d = new Date(x);
d.setDate(1);
d.setMonth(d.getMonth() + 1);
d.setDate(0);
return d.getDate();
}
/* For person born on birthDate, return their
** age on datumDate.
**
** Don't modify original date objects
**
** tDate is used as adding and subtracting
** years, months and days from dates on 29 February
** can affect the outcome,
**
** e.g.
**
** 2000-02-29 + 1 year => 2001-03-01
** 2001-03-01 - 1 year => 2000-03-01 so not symetric
**
** Note: in some systems, a person born on 29-Feb
** will have an official birthday on 28-Feb, other
** systems will have official birthday on 01-Mar.
*/
function getAge(birthDate, datumDate) {
// Make sure birthDate is before datumDate
if (birthDate - datumDate > 0) return null;
var dob = new Date(+birthDate),
now = new Date(+datumDate),
tDate = new Date(+dob),
dobY = dob.getFullYear(),
nowY = now.getFullYear(),
years, months, days;
// Initial estimate of years
years = nowY - dobY;
dobY = (dobY + years);
tDate.setYear(dobY);
// Correct if too many
if (now < tDate) {
--years;
--dobY;
}
dob.setYear(dobY);
// Repair tDate
tDate = new Date(+dob);
// Initial month estimate
months = now.getMonth() - tDate.getMonth();
// Adjust if needed
if (months < 0) {
months = 12 + months;
} else if (months == 0 && tDate.getDate() > now.getDate()) {
months = 11;
}
tDate.setMonth(tDate.getMonth() + months);
if (now < tDate) {
--months;
dob.setMonth(tDate.getMonth() - 1);
}
// Repair tDate
tDate = new Date(+dob);
// Initial day estimate
days = now.getDate() - tDate.getDate();
// Adjust if needed
if (days < 0) {
days = days + daysInMonth(tDate);
}
dob.setDate(dob.getDate() + days);
if (now < dob) {
--days;
}
return years + 'y ' + months + 'm ' + days + 'd';
}
function parseDMY(s) {
var b = s.split(/\D/);
var d = new Date(b[2], --b[1], b[0]);
return d && d.getMonth() == b[1]? d : new Date(NaN);
}
window.onload = function() {
var form = document.forms['ageCalc'];
form.onsubmit = function() {
var dob = parseDMY(form.dob.value);
form.age.value = isNaN(dob)? 'Invalid date' : getAge(dob, new Date());
return false;
}
}
<form id="ageCalc">
<table>
<tr>
<td>Date of Birth (d/m/y)
<td><input name="dob">
<tr>
<td>Age today (y, m, d)
<td><input readonly name="age">
<tr>
<td><input type="reset">
<td><input type="submit" value="Calculate Age">
</table>
</form>
Here's a straight years and days version:
function diffInYearsAndDays(startDate, endDate) {
// Copy and normalise dates
var d0 = new Date(startDate);
d0.setHours(12,0,0,0);
var d1 = new Date(endDate);
d1.setHours(12,0,0,0);
// Make d0 earlier date
// Can remember a sign here to make -ve if swapped
if (d0 > d1) {
var t = d0;
d0 = d1;
d1 = t;
}
// Initial estimate of years
var dY = d1.getFullYear() - d0.getFullYear();
// Modify start date
d0.setYear(d0.getFullYear() + dY);
// Adjust if required
if (d0 > d1) {
d0.setYear(d0.getFullYear() - 1);
--dY;
}
// Get remaining difference in days
var dD = (d1 - d0) / 8.64e7;
// If sign required, deal with it here
return [dY, dD];
}
alert(diffInYearsAndDays(new Date(1957, 11, 4), new Date(2012, 11, 2))); // [54, 364]

You could roll your own... but I would highly recommend something like Moment.js. It is a solid library that has been proven in the field for calculating Math like this. It is only 4k, so I think you will be fine on size also.

At end solution was not related to any libraty but logic. I set start age hours and minutes to same as current day hour and minute. Then I keep adding 12 months until year is over current. That was for counting full years. I then set last "birthday" that is not over current date to be info to take and use standard date difference in days against that date and current date.
It worked as charm.
Thanks everyone on great help. It helped me focus on topic.

Related

Subtracting 3 days from date

I want to calculate a reminderDate by subtracting 3 days from it. However, if the resulting date
falls on a Saturday or Sunday, it should give the date of the Friday
falls on a Friday, it should give the date of Thursday
For example
Exchange Date ReminderDate
18.06.2020 -3 days = 15.06.2020 --> OK, because Monday
17.06.2020 -3 days = 14.06.2020 --> Sunday, must be changed to 12.06.2020
16.06.2020 -3 days = 13.06.2020 --> Saturday, must be changed to 12.06.2020
15.06.2020 -3 days = 11.06.2020 --> Friday, must be changed to 11.06.2020
I tried something like this, but neither .getDay() nor .day() seem to work. And dt seems to give the date of today, and not the date of exchange.
var exchange = NWF$("#" + varAustauschtermin).val(); // date like 18.06.2020
console.log("Exchange: " + exchange);
var reminderDate = moment(exchange, "DD.MM.YYYY").format("DD.MM.YYYY");
var dt = new Date(reminderDate);
// var reminderDate = moment(exchange, "DD.MM.YYYY").subtract(3, 'days').format("DD.MM.YYYY");
// console.log("reminderDate.day(): " + reminderDate.day());
// console.log("reminderDate.getDay(): " + reminderDate.getDay());
if(dt.getDay() == 6) { // Saturday
console.log("Saturday");
reminderDate = moment(exchange, "DD.MM.YYYY").subtract(1, 'days').format("DD.MM.YYYY");
} else if (dt.getDay() == 0) { // Sunday
console.log("Sunday");
reminderDate = moment(exchange, "DD.MM.YYYY").subtract(2, 'days').format("DD.MM.YYYY");
} else if (dt.getDay() == 5) { // Friday
console.log("Friday");
reminderDate = moment(exchange, "DD.MM.YYYY").subtract(1, 'days').format("DD.MM.YYYY");
} else {
console.log("Weekday");
reminderDate = moment(exchange, "DD.MM.YYYY").subtract(3, 'days').format("DD.MM.YYYY");
}
console.log("Reminder Date: " + reminderDate);
Any help is appreciated!
If you are using momentjs then there is no need to switch to native Date object because everything you can do with momentjs and with much simplicity
Use momentjs day() to help you get the oridinal for a day of week
0 - Sunday
1 - Monday
...
..
.
6 - Saturday
To find what date will say "Saturday" come in this week you can do like moment().day("Saturday").
Then there is subtract which you are already using to rewind dates by given days.
Building on these above ideas you can try this helper function
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.0/moment.min.js"></script>
<script type="text/javascript">
function dateShift(d) {
//days numbering are 0(Sunday) to 6(Saturday)
d.subtract(3, 'days')
//Is SUNDAY?
if (d.day() == 0) {
//adjust it to friday
var upComingFri = d.day('Friday'); // date of friday in which THIS sunday is
return upComingFri.subtract(7, 'days');
//but we want to rewind as you want to stay in same week as the original date provided
}
//Is SATURDAY?
if (d.day() == 6) {
//adjust it to friday
var friday = d.day('Friday'); //sat is in same week
return friday;
}
//Is FRIDAY?
if (d.day() == 5) {
//adjust it to thursday
var thursday = d.day('Thursday');
return thursday;
}
return d;
}
t1 = moment('18.06.2020', "DD.MM.YYYY");
r1 = dateShift(t1);
console.log(r1.format("DD.MM.YYYY"))
t2 = moment('17.06.2020', "DD.MM.YYYY");
r2 = dateShift(t2);
console.log(r2.format("DD.MM.YYYY"))
t3 = moment('16.06.2020', "DD.MM.YYYY");
r3 = dateShift(t3);
console.log(r3.format("DD.MM.YYYY"))
t4 = moment('15.06.2020', "DD.MM.YYYY");
r4 = dateShift(t4);
console.log(r4.format("DD.MM.YYYY"))
</script>
It's not too hard to do this with plain javascript. Instead of subtracting 3 days, seeing what the day is, then subtracting again, you can work out the days to subtract given the initial day and do one subtraction, e.g.
// Parse string in format d.m.y to Date
function parseDMY(s) {
let [d, m, y] = s.split(/\D/);
return new Date(y, --m, d);
}
// s is date in format d.m.y
function adjustDate(s) {
let d = parseDMY(s);
// Subtract 4 days from Mon and Tue, 5 from Wed, 3 otherwise
d.setDate(d.getDate() - ([,4,4,5][d.getDay()] || 3));
return d;
}
['29.03.2020','28.03.2020','27.03.2020','26.03.2020',
'01.04.2020','31.03.2020','30.03.2020'
].forEach(s => console.log(parseDMY(s).toDateString() + ' -> ' +
adjustDate(s).toDateString()));

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

Show week number with Javascript?

I have the following code that is used to show the name of the current day, followed by a set phrase.
<script type="text/javascript">
<!--
// Array of day names
var dayNames = new Array(
"It's Sunday, the weekend is nearly over",
"Yay! Another Monday",
"Hello Tuesday, at least you're not Monday",
"It's Wednesday. Halfway through the week already",
"It's Thursday.",
"It's Friday - Hurray for the weekend",
"Saturday Night Fever");
var now = new Date();
document.write(dayNames[now.getDay()] + ".");
// -->
</script>
What I would like to do is have the current week number in brackets after the phrase. I have found the following code:
Date.prototype.getWeek = function() {
var onejan = new Date(this.getFullYear(),0,1);
return Math.ceil((((this - onejan) / 86400000) + onejan.getDay()+1)/7);
}
Which was taken from http://javascript.about.com/library/blweekyear.htm but I have no idea how to add it to existing javascript code.
Simply add it to your current code, then call (new Date()).getWeek()
<script>
Date.prototype.getWeek = function() {
var onejan = new Date(this.getFullYear(), 0, 1);
return Math.ceil((((this - onejan) / 86400000) + onejan.getDay() + 1) / 7);
}
var weekNumber = (new Date()).getWeek();
var dayNames = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
var now = new Date();
document.write(dayNames[now.getDay()] + " (" + weekNumber + ").");
</script>
In case you already use jQuery-UI (specifically datepicker):
Date.prototype.getWeek = function () { return $.datepicker.iso8601Week(this); }
Usage:
var myDate = new Date();
myDate.getWeek();
More here: UI/Datepicker/iso8601Week
I realize this isn't a general solution as it incurs a dependency. However, considering the popularity of jQuery-UI this might just be a simple fit for someone - as it was for me.
If you don't use jQuery-UI and have no intention of adding the dependency. You could just copy their iso8601Week() implementation since it is written in pure JavaScript without complex dependencies:
// Determine the week of the year (local timezone) based on the ISO 8601 definition.
Date.prototype.iso8601Week = function () {
// Create a copy of the current date, we don't want to mutate the original
const date = new Date(this.getTime());
// Find Thursday of this week starting on Monday
date.setDate(date.getDate() + 4 - (date.getDay() || 7));
const thursday = date.getTime();
// Find January 1st
date.setMonth(0); // January
date.setDate(1); // 1st
const jan1st = date.getTime();
// Round the amount of days to compensate for daylight saving time
const days = Math.round((thursday - jan1st) / 86400000); // 1 day = 86400000 ms
return Math.floor(days / 7) + 1;
};
console.log(new Date().iso8601Week());
console.log(new Date("2020-01-01T00:00").iso8601Week());
console.log(new Date("2021-01-01T00:00").iso8601Week());
console.log(new Date("2022-01-01T00:00").iso8601Week());
console.log(new Date("2023-12-31T00:00").iso8601Week());
console.log(new Date("2024-12-31T00:00").iso8601Week());
Consider using my implementation of "Date.prototype.getWeek", think is more accurate than the others i have seen here :)
Date.prototype.getWeek = function(){
// We have to compare against the first monday of the year not the 01/01
// 60*60*24*1000 = 86400000
// 'onejan_next_monday_time' reffers to the miliseconds of the next monday after 01/01
var day_miliseconds = 86400000,
onejan = new Date(this.getFullYear(),0,1,0,0,0),
onejan_day = (onejan.getDay()==0) ? 7 : onejan.getDay(),
days_for_next_monday = (8-onejan_day),
onejan_next_monday_time = onejan.getTime() + (days_for_next_monday * day_miliseconds),
// If one jan is not a monday, get the first monday of the year
first_monday_year_time = (onejan_day>1) ? onejan_next_monday_time : onejan.getTime(),
this_date = new Date(this.getFullYear(), this.getMonth(),this.getDate(),0,0,0),// This at 00:00:00
this_time = this_date.getTime(),
days_from_first_monday = Math.round(((this_time - first_monday_year_time) / day_miliseconds));
var first_monday_year = new Date(first_monday_year_time);
// We add 1 to "days_from_first_monday" because if "days_from_first_monday" is *7,
// then 7/7 = 1, and as we are 7 days from first monday,
// we should be in week number 2 instead of week number 1 (7/7=1)
// We consider week number as 52 when "days_from_first_monday" is lower than 0,
// that means the actual week started before the first monday so that means we are on the firsts
// days of the year (ex: we are on Friday 01/01, then "days_from_first_monday"=-3,
// so friday 01/01 is part of week number 52 from past year)
// "days_from_first_monday<=364" because (364+1)/7 == 52, if we are on day 365, then (365+1)/7 >= 52 (Math.ceil(366/7)=53) and thats wrong
return (days_from_first_monday>=0 && days_from_first_monday<364) ? Math.ceil((days_from_first_monday+1)/7) : 52;
}
You can check my public repo here https://bitbucket.org/agustinhaller/date.getweek (Tests included)
If you want something that works and is future-proof, use a library like MomentJS.
moment(date).week();
moment(date).isoWeek()
http://momentjs.com/docs/#/get-set/week/
It looks like this function I found at weeknumber.net is pretty accurate and easy to use.
// This script is released to the public domain and may be used, modified and
// distributed without restrictions. Attribution not necessary but appreciated.
// Source: http://weeknumber.net/how-to/javascript
// Returns the ISO week of the date.
Date.prototype.getWeek = function() {
var date = new Date(this.getTime());
date.setHours(0, 0, 0, 0);
// Thursday in current week decides the year.
date.setDate(date.getDate() + 3 - (date.getDay() + 6) % 7);
// January 4 is always in week 1.
var week1 = new Date(date.getFullYear(), 0, 4);
// Adjust to Thursday in week 1 and count number of weeks from date to week1.
return 1 + Math.round(((date.getTime() - week1.getTime()) / 86400000 - 3 + (week1.getDay() + 6) % 7) / 7);
}
If you're lucky like me and need to find the week number of the month a little adjust will do it:
// Returns the week in the month of the date.
Date.prototype.getWeekOfMonth = function() {
var date = new Date(this.getTime());
date.setHours(0, 0, 0, 0);
// Thursday in current week decides the year.
date.setDate(date.getDate() + 3 - (date.getDay() + 6) % 7);
// January 4 is always in week 1.
var week1 = new Date(date.getFullYear(), date.getMonth(), 4);
// Adjust to Thursday in week 1 and count number of weeks from date to week1.
return 1 + Math.round(((date.getTime() - week1.getTime()) / 86400000 - 3 + (week1.getDay() + 6) % 7) / 7);
}
If you already use Angular, then you could profit $filter('date').
For example:
var myDate = new Date();
var myWeek = $filter('date')(myDate, 'ww');
By adding the snippet you extend the Date object.
Date.prototype.getWeek = function() {
var onejan = new Date(this.getFullYear(),0,1);
return Math.ceil((((this - onejan) / 86400000) + onejan.getDay()+1)/7);
}
If you want to use this in multiple pages you can add this to a seperate js file which must be loaded first before your other scripts executes. With other scripts I mean the scripts which uses the getWeek() method.
All the proposed approaches may give wrong results because they don’t take into account summer/winter time changes. Rather than calculating the number of days between two dates using the constant of 86’400’000 milliseconds, it is better to use an approach like the following one:
getDaysDiff = function (dateObject0, dateObject1) {
if (dateObject0 >= dateObject1) return 0;
var d = new Date(dateObject0.getTime());
var nd = 0;
while (d <= dateObject1) {
d.setDate(d.getDate() + 1);
nd++;
}
return nd-1;
};
I was coding in the dark (a challenge) and couldn't lookup, bring in any dependencies or test my code.
I forgot what round up was called (Math.celi) So I wanted to be extra sure i got it right and came up with this code instead.
var elm = document.createElement('input')
elm.type = 'week'
elm.valueAsDate = new Date()
var week = elm.value.split('W').pop()
console.log(week)
Just a proof of concept of how you can get the week in any other way
But still i recommend any other solution that isn't required by the DOM.
With that code you can simply;
document.write(dayNames[now.getDay()] + " (" + now.getWeek() + ").");
(You will need to paste the getWeek function above your current script)
You could find this fiddle useful. Just finished.
https://jsfiddle.net/dnviti/ogpt920w/
Code below also:
/**
* Get the ISO week date week number
*/
Date.prototype.getWeek = function () {
// Create a copy of this date object
var target = new Date(this.valueOf());
// ISO week date weeks start on monday
// so correct the day number
var dayNr = (this.getDay() + 6) % 7;
// ISO 8601 states that week 1 is the week
// with the first thursday of that year.
// Set the target date to the thursday in the target week
target.setDate(target.getDate() - dayNr + 3);
// Store the millisecond value of the target date
var firstThursday = target.valueOf();
// Set the target to the first thursday of the year
// First set the target to january first
target.setMonth(0, 1);
// Not a thursday? Correct the date to the next thursday
if (target.getDay() != 4) {
target.setMonth(0, 1 + ((4 - target.getDay()) + 7) % 7);
}
// The weeknumber is the number of weeks between the
// first thursday of the year and the thursday in the target week
return 1 + Math.ceil((firstThursday - target) / 604800000); // 604800000 = 7 * 24 * 3600 * 1000
}
/**
* Get the ISO week date year number
*/
Date.prototype.getWeekYear = function ()
{
// Create a new date object for the thursday of this week
var target = new Date(this.valueOf());
target.setDate(target.getDate() - ((this.getDay() + 6) % 7) + 3);
return target.getFullYear();
}
/**
* Convert ISO week number and year into date (first day of week)
*/
var getDateFromISOWeek = function(w, y) {
var simple = new Date(y, 0, 1 + (w - 1) * 7);
var dow = simple.getDay();
var ISOweekStart = simple;
if (dow <= 4)
ISOweekStart.setDate(simple.getDate() - simple.getDay() + 1);
else
ISOweekStart.setDate(simple.getDate() + 8 - simple.getDay());
return ISOweekStart;
}
var printDate = function(){
/*var dateString = document.getElementById("date").value;
var dateArray = dateString.split("/");*/ // use this if you have year-week in the same field
var dateInput = document.getElementById("date").value;
if (dateInput == ""){
var date = new Date(); // get today date object
}
else{
var date = new Date(dateInput); // get date from field
}
var day = ("0" + date.getDate()).slice(-2); // get today day
var month = ("0" + (date.getMonth() + 1)).slice(-2); // get today month
var fullDate = date.getFullYear()+"-"+(month)+"-"+(day) ; // get full date
var year = date.getFullYear();
var week = ("0" + (date.getWeek())).slice(-2);
var locale= "it-it";
document.getElementById("date").value = fullDate; // set input field
document.getElementById("year").value = year;
document.getElementById("week").value = week; // this prototype has been written above
var fromISODate = getDateFromISOWeek(week, year);
var fromISODay = ("0" + fromISODate.getDate()).slice(-2);
var fromISOMonth = ("0" + (fromISODate.getMonth() + 1)).slice(-2);
var fromISOYear = date.getFullYear();
// Use long to return month like "December" or short for "Dec"
//var monthComplete = fullDate.toLocaleString(locale, { month: "long" });
var formattedDate = fromISODay + "-" + fromISOMonth + "-" + fromISOYear;
var element = document.getElementById("fullDate");
element.value = formattedDate;
}
printDate();
document.getElementById("convertToDate").addEventListener("click", printDate);
*{
font-family: consolas
}
<label for="date">Date</label>
<input type="date" name="date" id="date" style="width:130px;text-align:center" value="" />
<br /><br />
<label for="year">Year</label>
<input type="year" name="year" id="year" style="width:40px;text-align:center" value="" />
-
<label for="week">Week</label>
<input type="text" id="week" style="width:25px;text-align:center" value="" />
<br /><br />
<label for="fullDate">Full Date</label>
<input type="text" id="fullDate" name="fullDate" style="width:80px;text-align:center" value="" />
<br /><br />
<button id="convertToDate">
Convert Date
</button>
It's pure JS.
There are a bunch of date functions inside that allow you to convert date into week number and viceversa :)
Luxon is an other alternative. Luxon date objects have a weekNumber property:
let week = luxon.DateTime.fromString("2022-04-01", "yyyy-MM-dd").weekNumber;
console.log(week);
<script src="https://cdnjs.cloudflare.com/ajax/libs/luxon/3.0.1/luxon.min.js"></script>
I've tried using code from all of the answers above, and all return week #52 for the first of January. So I decided to write my own, which calculates the week number correctly.
Week numeration starts from 0
Maybe it's a bad taste to use a loop, or the result can be cached somewhere to prevent repeating the same calculations if the function is called often enough. Well, I have made this for myself, and it does what I need it to do.
Date.prototype.getWeek = function() {
// debugger
let msWeek = 604800000; // Week in milliseconds
let msDay = 86400000; // Day in milliseconds
let year = this.getFullYear(); // Get the year
//let month = this.getMonth(); // Month
let oneDate = new Date(year, 0, 1); // Create a new date based on THIS year
let temp = oneDate.getDay(); // Ordinal of the first day
let getFirstDay = (temp === 0) ? 6 : temp - 1; // Ordinal of the first day of the current month (0-MO, 6-SU)
let countWeek = 0;
// Test to confirm week
oneDate = new Date(oneDate.getTime() + msDay*(7 - getFirstDay));
if(oneDate.getTime() > this.getTime()){
return countWeek;
}
// Increment loop
while(true){
oneDate = new Date(oneDate.getTime() + msWeek); // Add a week and check
if(oneDate.getTime() > this.getTime()) break;
countWeek++;
}
return countWeek + 1;
}
let s1 = new Date('2022-01-01'); console.log(s1.getWeek());
let s2 = new Date('2023-01-01'); console.log(s2.getWeek());
let s22 = new Date('2023-01-02'); console.log(s22.getWeek());
let s3 = new Date('2024-01-01'); console.log(s3.getWeek());
let s4 = new Date('2025-01-01'); console.log(s4.getWeek());
let s5 = new Date('2022-02-28'); console.log(s5.getWeek());
let s6 = new Date('2022-12-31'); console.log(s6.getWeek());
let s7 = new Date('2024-12-31'); console.log(s7.getWeek());
Some of the code I see in here fails with years like 2016, in which week 53 jumps to week 2.
Here is a revised and working version:
Date.prototype.getWeek = function() {
// Create a copy of this date object
var target = new Date(this.valueOf());
// ISO week date weeks start on monday, so correct the day number
var dayNr = (this.getDay() + 6) % 7;
// Set the target to the thursday of this week so the
// target date is in the right year
target.setDate(target.getDate() - dayNr + 3);
// ISO 8601 states that week 1 is the week with january 4th in it
var jan4 = new Date(target.getFullYear(), 0, 4);
// Number of days between target date and january 4th
var dayDiff = (target - jan4) / 86400000;
if(new Date(target.getFullYear(), 0, 1).getDay() < 5) {
// Calculate week number: Week 1 (january 4th) plus the
// number of weeks between target date and january 4th
return 1 + Math.ceil(dayDiff / 7);
}
else { // jan 4th is on the next week (so next week is week 1)
return Math.ceil(dayDiff / 7);
}
};
Martin Schillinger's version seems to be the strictly correct one.
Since I knew I only needed it to work correctly on business week days, I went with this simpler form, based on something I found online, don't remember where:
ISOWeekday = (0 == InputDate.getDay()) ? 7 : InputDate.getDay();
ISOCalendarWeek = Math.floor( ( ((InputDate.getTime() - (new Date(InputDate.getFullYear(),0,1)).getTime()) / 86400000) - ISOWeekday + 10) / 7 );
It fails in early January on days that belong to the previous year's last week (it produces CW = 0 in those cases) but is correct for everything else.

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();

Difference in Months between two dates in JavaScript

How would I work out the difference for two Date() objects in JavaScript, while only return the number of months in the difference?
Any help would be great :)
The definition of "the number of months in the difference" is subject to a lot of interpretation. :-)
You can get the year, month, and day of month from a JavaScript date object. Depending on what information you're looking for, you can use those to figure out how many months are between two points in time.
For instance, off-the-cuff:
function monthDiff(d1, d2) {
var months;
months = (d2.getFullYear() - d1.getFullYear()) * 12;
months -= d1.getMonth();
months += d2.getMonth();
return months <= 0 ? 0 : months;
}
function monthDiff(d1, d2) {
var months;
months = (d2.getFullYear() - d1.getFullYear()) * 12;
months -= d1.getMonth();
months += d2.getMonth();
return months <= 0 ? 0 : months;
}
function test(d1, d2) {
var diff = monthDiff(d1, d2);
console.log(
d1.toISOString().substring(0, 10),
"to",
d2.toISOString().substring(0, 10),
":",
diff
);
}
test(
new Date(2008, 10, 4), // November 4th, 2008
new Date(2010, 2, 12) // March 12th, 2010
);
// Result: 16
test(
new Date(2010, 0, 1), // January 1st, 2010
new Date(2010, 2, 12) // March 12th, 2010
);
// Result: 2
test(
new Date(2010, 1, 1), // February 1st, 2010
new Date(2010, 2, 12) // March 12th, 2010
);
// Result: 1
(Note that month values in JavaScript start with 0 = January.)
Including fractional months in the above is much more complicated, because three days in a typical February is a larger fraction of that month (~10.714%) than three days in August (~9.677%), and of course even February is a moving target depending on whether it's a leap year.
There are also some date and time libraries available for JavaScript that probably make this sort of thing easier.
Note: There used to be a + 1 in the above, here:
months = (d2.getFullYear() - d1.getFullYear()) * 12;
months -= d1.getMonth() + 1;
// −−−−−−−−−−−−−−−−−−−−^^^^
months += d2.getMonth();
That's because originally I said:
...this finds out how many full months lie between two dates, not counting partial months (e.g., excluding the month each date is in).
I've removed it for two reasons:
Not counting partial months turns out not to be what many (most?) people coming to the answer want, so I thought I should separate them out.
It didn't always work even by that definition. :-D (Sorry.)
If you do not consider the day of the month, this is by far the simpler solution
function monthDiff(dateFrom, dateTo) {
return dateTo.getMonth() - dateFrom.getMonth() +
(12 * (dateTo.getFullYear() - dateFrom.getFullYear()))
}
//examples
console.log(monthDiff(new Date(2000, 01), new Date(2000, 02))) // 1
console.log(monthDiff(new Date(1999, 02), new Date(2000, 02))) // 12 full year
console.log(monthDiff(new Date(2009, 11), new Date(2010, 0))) // 1
Be aware that month index is 0-based. This means that January = 0 and December = 11.
Here's a function that accurately provides the number of months between 2 dates.
The default behavior only counts whole months, e.g. 3 months and 1 day will result in a difference of 3 months. You can prevent this by setting the roundUpFractionalMonths param as true, so a 3 month and 1 day difference will be returned as 4 months.
The accepted answer above (T.J. Crowder's answer) isn't accurate, it returns wrong values sometimes.
For example, monthDiff(new Date('Jul 01, 2015'), new Date('Aug 05, 2015')) returns 0 which is obviously wrong. The correct difference is either 1 whole month or 2 months rounded-up.
Here's the function I wrote:
function getMonthsBetween(date1,date2,roundUpFractionalMonths)
{
//Months will be calculated between start and end dates.
//Make sure start date is less than end date.
//But remember if the difference should be negative.
var startDate=date1;
var endDate=date2;
var inverse=false;
if(date1>date2)
{
startDate=date2;
endDate=date1;
inverse=true;
}
//Calculate the differences between the start and end dates
var yearsDifference=endDate.getFullYear()-startDate.getFullYear();
var monthsDifference=endDate.getMonth()-startDate.getMonth();
var daysDifference=endDate.getDate()-startDate.getDate();
var monthCorrection=0;
//If roundUpFractionalMonths is true, check if an extra month needs to be added from rounding up.
//The difference is done by ceiling (round up), e.g. 3 months and 1 day will be 4 months.
if(roundUpFractionalMonths===true && daysDifference>0)
{
monthCorrection=1;
}
//If the day difference between the 2 months is negative, the last month is not a whole month.
else if(roundUpFractionalMonths!==true && daysDifference<0)
{
monthCorrection=-1;
}
return (inverse?-1:1)*(yearsDifference*12+monthsDifference+monthCorrection);
};
Sometimes you may want to get just the quantity of the months between two dates totally ignoring the day part. So for instance, if you had two dates- 2013/06/21 and 2013/10/18- and you only cared about the 2013/06 and 2013/10 parts, here are the scenarios and possible solutions:
var date1=new Date(2013,5,21);//Remember, months are 0 based in JS
var date2=new Date(2013,9,18);
var year1=date1.getFullYear();
var year2=date2.getFullYear();
var month1=date1.getMonth();
var month2=date2.getMonth();
if(month1===0){ //Have to take into account
month1++;
month2++;
}
var numberOfMonths;
1.If you want just the number of the months between the two dates excluding both month1 and month2
numberOfMonths = (year2 - year1) * 12 + (month2 - month1) - 1;
2.If you want to include either of the months
numberOfMonths = (year2 - year1) * 12 + (month2 - month1);
3.If you want to include both of the months
numberOfMonths = (year2 - year1) * 12 + (month2 - month1) + 1;
If you need to count full months, regardless of the month being 28, 29, 30 or 31 days. Below should work.
var months = to.getMonth() - from.getMonth()
+ (12 * (to.getFullYear() - from.getFullYear()));
if(to.getDate() < from.getDate()){
months--;
}
return months;
This is an extended version of the answer https://stackoverflow.com/a/4312956/1987208 but fixes the case where it calculates 1 month for the case from 31st of January to 1st of February (1day).
This will cover the following;
1st Jan to 31st Jan ---> 30days ---> will result in 0 (logical since it is not a full month)
1st Feb to 1st Mar ---> 28 or 29 days ---> will result in 1 (logical since it is a full month)
15th Feb to 15th Mar ---> 28 or 29 days ---> will result in 1 (logical since a month passed)
31st Jan to 1st Feb ---> 1 day ---> will result in 0 (obvious but the mentioned answer in the post results in 1 month)
Difference in Months between two dates in JavaScript:
start_date = new Date(year, month, day); //Create start date object by passing appropiate argument
end_date = new Date(new Date(year, month, day)
total months between start_date and end_date :
total_months = (end_date.getFullYear() - start_date.getFullYear())*12 + (end_date.getMonth() - start_date.getMonth())
I know this is really late, but posting it anyway just in case it helps others. Here is a function I came up with that seems to do a good job of counting differences in months between two dates. It is admittedly a great deal raunchier than Mr.Crowder's, but provides more accurate results by stepping through the date object. It is in AS3 but you should just be able to drop the strong typing and you'll have JS. Feel free to make it nicer looking anyone out there!
function countMonths ( startDate:Date, endDate:Date ):int
{
var stepDate:Date = new Date;
stepDate.time = startDate.time;
var monthCount:int;
while( stepDate.time <= endDate.time ) {
stepDate.month += 1;
monthCount += 1;
}
if ( stepDate != endDate ) {
monthCount -= 1;
}
return monthCount;
}
You could also consider this solution, this function returns the month difference in integer or number
Passing the start date as the first or last param, is fault tolerant. Meaning, the function would still return the same value.
const diffInMonths = (end, start) => {
var timeDiff = Math.abs(end.getTime() - start.getTime());
return Math.round(timeDiff / (2e3 * 3600 * 365.25));
}
const result = diffInMonths(new Date(2015, 3, 28), new Date(2010, 1, 25));
// shows month difference as integer/number
console.log(result);
To expand on #T.J.'s answer, if you're looking for simple months, rather than full calendar months, you could just check if d2's date is greater than or equal to than d1's. That is, if d2 is later in its month than d1 is in its month, then there is 1 more month. So you should be able to just do this:
function monthDiff(d1, d2) {
var months;
months = (d2.getFullYear() - d1.getFullYear()) * 12;
months -= d1.getMonth() + 1;
months += d2.getMonth();
// edit: increment months if d2 comes later in its month than d1 in its month
if (d2.getDate() >= d1.getDate())
months++
// end edit
return months <= 0 ? 0 : months;
}
monthDiff(
new Date(2008, 10, 4), // November 4th, 2008
new Date(2010, 2, 12) // March 12th, 2010
);
// Result: 16; 4 Nov – 4 Dec '08, 4 Dec '08 – 4 Dec '09, 4 Dec '09 – 4 March '10
This doesn't totally account for time issues (e.g. 3 March at 4:00pm and 3 April at 3:00pm), but it's more accurate and for just a couple lines of code.
Consider each date in terms of months, then subtract to find the difference.
var past_date = new Date('11/1/2014');
var current_date = new Date();
var difference = (current_date.getFullYear()*12 + current_date.getMonth()) - (past_date.getFullYear()*12 + past_date.getMonth());
This will get you the difference of months between the two dates, ignoring the days.
There are two approaches, mathematical & quick, but subject to vagaries in the calendar, or iterative & slow, but handles all the oddities (or at least delegates handling them to a well-tested library).
If you iterate through the calendar, incrementing the start date by one month & seeing if we pass the end date. This delegates anomaly-handling to the built-in Date() classes, but could be slow IF you're doing this for a large number of dates. James' answer takes this approach. As much as I dislike the idea, I think this is the "safest" approach, and if you're only doing one calculation, the performance difference really is negligible. We tend to try to over-optimize tasks which will only be performed once.
Now, if you're calculating this function on a dataset, you probably don't want to run that function on each row (or god forbid, multiple times per record). In that case, you can use almost any of the other answers here except the accepted answer, which is just wrong (difference between new Date() and new Date() is -1)?
Here's my stab at a mathematical-and-quick approach, which accounts for differing month lengths and leap years. You really should only use a function like this if you'll be applying this to a dataset (doing this calculation over & over). If you just need to do it once, use James' iterative approach above, as you're delegating handling all the (many) exceptions to the Date() object.
function diffInMonths(from, to){
var months = to.getMonth() - from.getMonth() + (12 * (to.getFullYear() - from.getFullYear()));
if(to.getDate() < from.getDate()){
var newFrom = new Date(to.getFullYear(),to.getMonth(),from.getDate());
if (to < newFrom && to.getMonth() == newFrom.getMonth() && to.getYear() %4 != 0){
months--;
}
}
return months;
}
Calculate the difference between two dates include fraction of month (days).
var difference = (date2.getDate() - date1.getDate()) / 30 +
date2.getMonth() - date1.getMonth() +
(12 * (date2.getFullYear() - date1.getFullYear()));
For example:
date1: 24/09/2015 (24th Sept 2015)
date2: 09/11/2015 (9th Nov 2015)
the difference: 2.5 (months)
Here you go other approach with less looping:
calculateTotalMonthsDifference = function(firstDate, secondDate) {
var fm = firstDate.getMonth();
var fy = firstDate.getFullYear();
var sm = secondDate.getMonth();
var sy = secondDate.getFullYear();
var months = Math.abs(((fy - sy) * 12) + fm - sm);
var firstBefore = firstDate > secondDate;
firstDate.setFullYear(sy);
firstDate.setMonth(sm);
firstBefore ? firstDate < secondDate ? months-- : "" : secondDate < firstDate ? months-- : "";
return months;
}
This should work fine:
function monthDiff(d1, d2) {
var months;
months = (d2.getFullYear() - d1.getFullYear()) * 12;
months += d2.getMonth() - d1.getMonth();
return months;
}
Number Of Months When Day & Time Doesn't Matter
In this case, I'm not concerned with full months, part months, how long a month is, etc. I just need to know the number of months. A relevant real world case would be where a report is due every month, and I need to know how many reports there should be.
Example:
January = 1 month
January - February = 2 months
November - January = 3 months
This is an elaborated code example to show where the numbers are going.
Let's take 2 timestamps that should result in 4 months
November 13, 2019's timestamp: 1573621200000
February 20, 2020's timestamp: 1582261140000
May be slightly different with your timezone / time pulled. The day, minutes, and seconds don't matter and can be included in the timestamp, but we will disregard it with our actual calculation.
Step 1: convert the timestamp to a JavaScript date
let dateRangeStartConverted = new Date(1573621200000);
let dateRangeEndConverted = new Date(1582261140000);
Step 2: get integer values for the months / years
let startingMonth = dateRangeStartConverted.getMonth();
let startingYear = dateRangeStartConverted.getFullYear();
let endingMonth = dateRangeEndConverted.getMonth();
let endingYear = dateRangeEndConverted.getFullYear();
This gives us
Starting month: 11
Starting Year: 2019
Ending month: 2
Ending Year: 2020
Step 3: Add (12 * (endYear - startYear)) + 1 to the ending month.
This makes our starting month stay at 11
This makes our ending month equal 15 2 + (12 * (2020 - 2019)) + 1 = 15
Step 4: Subtract the months
15 - 11 = 4; we get our 4 month result.
29 Month Example Example
November 2019 through March 2022 is 29 months. If you put these into an excel spreadsheet, you will see 29 rows.
Our starting month is 11
Our ending month is 40 3 + (12 * (2022-2019)) + 1
40 - 11 = 29
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);
}
Following code returns full months between two dates by taking nr of days of partial months into account as well.
var monthDiff = function(d1, d2) {
if( d2 < d1 ) {
var dTmp = d2;
d2 = d1;
d1 = dTmp;
}
var months = (d2.getFullYear() - d1.getFullYear()) * 12;
months -= d1.getMonth() + 1;
months += d2.getMonth();
if( d1.getDate() <= d2.getDate() ) months += 1;
return months;
}
monthDiff(new Date(2015, 01, 20), new Date(2015, 02, 20))
> 1
monthDiff(new Date(2015, 01, 20), new Date(2015, 02, 19))
> 0
monthDiff(new Date(2015, 01, 20), new Date(2015, 01, 22))
> 0
function monthDiff(d1, d2) {
var months, d1day, d2day, d1new, d2new, diffdate,d2month,d2year,d1maxday,d2maxday;
months = (d2.getFullYear() - d1.getFullYear()) * 12;
months -= d1.getMonth() + 1;
months += d2.getMonth();
months = (months <= 0 ? 0 : months);
d1day = d1.getDate();
d2day = d2.getDate();
if(d1day > d2day)
{
d2month = d2.getMonth();
d2year = d2.getFullYear();
d1new = new Date(d2year, d2month-1, d1day,0,0,0,0);
var timeDiff = Math.abs(d2.getTime() - d1new.getTime());
diffdate = Math.abs(Math.ceil(timeDiff / (1000 * 3600 * 24)));
d1new = new Date(d2year, d2month, 1,0,0,0,0);
d1new.setDate(d1new.getDate()-1);
d1maxday = d1new.getDate();
months += diffdate / d1maxday;
}
else
{
if(!(d1.getMonth() == d2.getMonth() && d1.getFullYear() == d2.getFullYear()))
{
months += 1;
}
diffdate = d2day - d1day + 1;
d2month = d2.getMonth();
d2year = d2.getFullYear();
d2new = new Date(d2year, d2month + 1, 1, 0, 0, 0, 0);
d2new.setDate(d2new.getDate()-1);
d2maxday = d2new.getDate();
months += diffdate / d2maxday;
}
return months;
}
below logic will fetch difference in months
(endDate.getFullYear()*12+endDate.getMonth())-(startDate.getFullYear()*12+startDate.getMonth())
function monthDiff(date1, date2, countDays) {
countDays = (typeof countDays !== 'undefined') ? countDays : false;
if (!date1 || !date2) {
return 0;
}
let bigDate = date1;
let smallDate = date2;
if (date1 < date2) {
bigDate = date2;
smallDate = date1;
}
let monthsCount = (bigDate.getFullYear() - smallDate.getFullYear()) * 12 + (bigDate.getMonth() - smallDate.getMonth());
if (countDays && bigDate.getDate() < smallDate.getDate()) {
--monthsCount;
}
return monthsCount;
}
This is the simplest solution I could find. This will directly return the number of months. Although, it always gives an absolute value.
new Date(new Date(d2) - new Date(d1)).getMonth();
For non-absolute values, you can use the following solution:
function diff_months(startDate, endDate) {
let diff = new Date( new Date(endDate) - new Date(startDate) ).getMonth();
return endDate >= startDate ? diff : -diff;
}
See what I use:
function monthDiff() {
var startdate = Date.parseExact($("#startingDate").val(), "dd/MM/yyyy");
var enddate = Date.parseExact($("#endingDate").val(), "dd/MM/yyyy");
var months = 0;
while (startdate < enddate) {
if (startdate.getMonth() === 1 && startdate.getDate() === 28) {
months++;
startdate.addMonths(1);
startdate.addDays(2);
} else {
months++;
startdate.addMonths(1);
}
}
return months;
}
It also counts the days and convert them in months.
function monthDiff(d1, d2) {
var months;
months = (d2.getFullYear() - d1.getFullYear()) * 12; //calculates months between two years
months -= d1.getMonth() + 1;
months += d2.getMonth(); //calculates number of complete months between two months
day1 = 30-d1.getDate();
day2 = day1 + d2.getDate();
months += parseInt(day2/30); //calculates no of complete months lie between two dates
return months <= 0 ? 0 : months;
}
monthDiff(
new Date(2017, 8, 8), // Aug 8th, 2017 (d1)
new Date(2017, 12, 12) // Dec 12th, 2017 (d2)
);
//return value will be 4 months
getMonthDiff(d1, d2) {
var year1 = dt1.getFullYear();
var year2 = dt2.getFullYear();
var month1 = dt1.getMonth();
var month2 = dt2.getMonth();
var day1 = dt1.getDate();
var day2 = dt2.getDate();
var months = month2 - month1;
var years = year2 -year1
days = day2 - day1;
if (days < 0) {
months -= 1;
}
if (months < 0) {
months += 12;
}
return months + years*!2;
}
Any value is returned along with its absolute value.
function differenceInMonths(firstDate, secondDate) {
if (firstDate > secondDate) [firstDate, secondDate] = [secondDate, firstDate];
let diffMonths = (secondDate.getFullYear() - firstDate.getFullYear()) * 12;
diffMonths -= firstDate.getMonth();
diffMonths += secondDate.getMonth();
return diffMonths;
}
The following code snippet helped me to find months between two dates
Find Months Count Between two dates JS
Months Between two dates JS
Code Snippet
function diff_months_count(startDate, endDate) {
var months;
var d1 = new Date(startDate);
var d2 = new Date(endDate);
months = (d2.getFullYear() - d1.getFullYear()) * 12;
months -= d1.getMonth();
months += d2.getMonth();
return months <= 0 ? 0 : months;
}
#Here is a nice piece of code i wrote for getting number of days and months
from given dates
[1]: jsfiddle link
/**
* Date a end day
* Date b start day
* #param DateA Date #param DateB Date
* #returns Date difference
*/
function getDateDifference(dateA, DateB, type = 'month') {
const END_DAY = new Date(dateA)
const START_DAY = new Date(DateB)
let calculatedDateBy
let returnDateDiff
if (type === 'month') {
const startMonth = START_DAY.getMonth()
const endMonth = END_DAY.getMonth()
calculatedDateBy = startMonth - endMonth
returnDateDiff = Math.abs(
calculatedDateBy + 12 * (START_DAY.getFullYear() - END_DAY.getFullYear())
)
} else {
calculatedDateBy = Math.abs(START_DAY - END_DAY)
returnDateDiff = Math.ceil(calculatedDateBy / (1000 * 60 * 60 * 24))
}
const out = document.getElementById('output')
out.innerText = returnDateDiff
return returnDateDiff
}
// Gets number of days from given dates
/* getDateDifference('2022-03-31','2022-04-08','day') */
// Get number of months from given dates
getDateDifference('2021-12-02','2022-04-08','month')
<div id="output"> </div>
anyVar = (((DisplayTo.getFullYear() * 12) + DisplayTo.getMonth()) - ((DisplayFrom.getFullYear() * 12) + DisplayFrom.getMonth()));
One approach would be to write a simple Java Web Service (REST/JSON) that uses JODA library
http://joda-time.sourceforge.net/faq.html#datediff
to calculate difference between two dates and call that service from javascript.
This assumes your back end is in Java.

Categories

Resources