Get the number of days between 2 dates using Javascript - javascript

actually the code works fine when the date is on the same month but i had a problem when the date is on the different month like 30/09/2015 and 01/10/2015 the number of days result is 2.(sorry for my bad english)
Here's the sample code:
var dtElem1 = '30/09/2015';
var dtElem2 = '01/10/2015';
var resultElem = frm.elements['numberofdays'];
var oneDay = 24*60*60*1000;
var x = dtElem1.value;
var y = dtElem2.value;
var arr1 = x.split('/');
var arr2 = y.split('/');
var dt1 = new Date();
dt1.setFullYear(arr1[2], arr1[1], arr1[0]);
var dt2 = new Date();
dt2.setFullYear(arr2[2], arr2[1], arr2[0]);
resultElem.value = Math.round(Math.abs((dt1.getTime() -
dt2.getTime())/(oneDay)));

The Date methods count months from zero, so you should substract 1 from the month number when setting the date. That explains your bug, since you end up substracting the 30th of october from the 1st of november and october has 31 days.
This will give the expected result:
dt1.setFullYear(arr1[2], arr1[1] - 1, arr1[0])
dt2.setFullYear(arr2[2], arr2[1] - 1, arr2[0])
Note that you don't need to create the Date and then set it. You can pass the same arguments directly to the constructor:
dt1 = new Date(arr1[2], arr1[1] - 1, arr1[0])
dt2 = new Date(arr2[2], arr2[1] - 1, arr2[0])

Related

Date calculation using javaScript

I need date algorithms, Which will display me how long I have been given a date anywhere.
Example:
Suppose
Today is 01/06/2019 (dd/mm/yy)
BirthDate is 31/05/2019 (dd/mm/yy)
Now, My age is 1 day 0 Months and 0 years
[NOTE: I need all of them, It means day/month and years]
I have been read at least 23 articles/post in this site but they only give years or month or date but not everything in one...
var date, cDate, cMonth, cYears, oDate, oMonth, oYears;
date = new Date()
//current date
cDate = date.getDate()
cMonth = date.getMonth()
cYears = date.getFullYear()
//birth date
oDate = 01
oMonth = 05
oYears = 2019
(Multiplying is not the main solution I think so, need to work with all arithmetics operator)
This will give you the result you need
var birth = new Date("5/31/2019"); // mm/dd/year
var today = new Date();
var diff = today.valueOf()-birth.valueOf();
var result = new Date(diff);
var dayDiff = result.getDate() - 1; //because epoch start from 1st
var yearDiff = result.getFullYear() - 1970; //because epoch start from 1970
var str = `${dayDiff} day ${result.getMonth()} Months and ${yearDiff} years`;
console.log(str);
You should use moment, so there you can do:
var a = moment("04/09/2019 15:00:00");
var b = moment("04/09/2013 14:20:30");
console.log(a.diff(b, 'years'))
console.log(a.diff(b, 'months'))
console.log(a.diff(b, 'days'))
Similarly, you can get minutes, hours and seconds if you need.
While using the library moment.js

Moment.js Duration between Two Dates

How do I get the time difference between two different dates variables, specifically in years, months and days using moment.js?
I found this method but I keep getting weird results. Sometimes the result is one month ahead so I added a subtract one months part to make the result correct, but when the difference between the two dates can be divided into whole years it then becomes a month behind, but then if I remove the subtract month part, it gets even more out of whack.
Also I would like to format it as "X Years, Y Months, Z days", but also can't figure out how to format it in such way.
var dateOne = new Date(2000,07,16);
var dateTwo = new Date (1990,07,16);
var updatedDate = moment(dateOne).format('ll');
var x = moment(dateOne, 'DD/MM/YYYY').diff(moment(dateTwo, 'DD/MM/YYYY'))
var y = moment.duration(x);
var why = moment(x).subtract(1, 'M');
var z = Math.floor(y.asYears()) + moment.utc(why).format('/MM/DD');
console.log(z);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
Try this perhaps?
var firstDate = moment();
var secondDate = moment("2018-03-19");
var yearDiff = firstDate.diff(secondDate, "year");
var monthDiff = firstDate.diff(secondDate, "month");
var dayDiff = firstDate.diff(secondDate, "day");
console.log(yearDiff + " Years, " + monthDiff + " Months, " + dayDiff + " Days");
https://jsfiddle.net/px1brLdk/
As stated by others in the comments, you can't format a duration as a date and since dateOne and dateTwo are a Date objects, there is no need for the second argument in moment(dateOne, 'DD/MM/YYYY'), simply use moment(Date).
Moverover, please note that when you use new Date(year, monthIndex, day) monthIndex starts from 0, see MDN docs:
The argument monthIndex is 0-based. This means that January = 0 and December = 11.
You can use moment-duration-format plug-in to format momentjs duration according your needs, see format() docs on the plug-in page.
Here a live sample:
var dateOne = new Date(2000, 7, 16);
var dateTwo = new Date(1990, 7, 16);
var diff = moment(dateOne).diff(moment(dateTwo))
var dur = moment.duration(diff);
var result = dur.format();
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-duration-format/2.2.2/moment-duration-format.min.js"></script>
Moment is having a method called .diff() Use that one.
https://momentjs.com/docs/#/displaying/difference/

How to get the Week wise Start and End date in angularjs

Before I am using angularjs-DatePicker from this npm.
Here,I am able to select the date from the date picker.But now I have to fields as FromDate and ToDate which means the week StartDate and EndDate should show when any date pick in that week.
Ex: Like in Calender 01-08-2017 Start on Tue, So whenever Selects Any date from 01 to 05 then the two fields should show as FromDate as 01 and TODate as 06 and in the same whenever the user selects the 31-07-2017 the the Two fields should show as 30 and 31 of july.
I have an idea to achieve the ToDate from FromDate Calender control onchange event in DotNet as like below mentioned code
Convert.ToDouble(objstart.DayOfWeek)).ToString("dd-MM-yyyy")
But how to achieve this usecase in the angularjs.
Thanks
Ok, so what I'd do is to calculate different dates, and take the min/max depending on the start or end of the week.
Here:
//Use the date received, UTC to prevent timezone making dates shift
var pickedDate = new Date("08-03-2017UTC");
var startSunday = new Date(pickedDate);
startSunday.setDate(pickedDate.getDate() - pickedDate.getDay());
var startMonth = new Date(pickedDate);
startMonth.setDate(1);
var startDate = Math.max(startMonth,startSunday);
console.log("Start:" , new Date(startDate));
var endSaturday = new Date(pickedDate);
endSaturday.setDate(pickedDate.getDate() + (7-pickedDate.getDay()));
var endMonth = new Date(pickedDate);
endMonth.setMonth(pickedDate.getMonth()+1);//Add a month
endMonth.setDate(0);// to select last day of previous month.
var endDate = Math.min(endMonth,endSaturday);
console.log("End" , new Date(endDate));
The trick was to play with the dates, find all the possible start and end dates, then choose the right one with Math.min and Math.max which will compare the dates using their timestamp.
There is very good Library available in JavaScript to handle Date Manipulations.
https://github.com/datejs/Datejs
There is a method
Date.parse('next friday') // Returns the date of the next Friday.
Date.parse('last monday')
Using these method you can get the start and ending date of the week based on the current week.
I hope that it will help.
You can simply achieve this using the library moment. There are a lot of useful functions in this library.
var selectedDate = moment('Mon Aug 10 2017');
//If you want to get the ISO week format(Monday to Sunday)
var weekStart = selectedDate.clone().startOf('isoweek').format('MMM Do');
var weekEnd = selectedDate.clone().endOf('isoweek').format('MMM Do');
//If you want to get the Sunday to Saturday week format
var weekStart = selectedDate.clone().startOf('week').format('MMM Do');
var weekEnd = selectedDate.clone().endOf('week').format('MMM Do');
No need angular directive here, you could use the JavaScript extension which is below.
//get week from date
Date.prototype.getWeekNumber = function (weekstart) {
var target = new Date(this.valueOf());
// Set default for weekstart and clamp to useful range
if (weekstart === undefined) weekstart = 1;
weekstart %= 7;
// Replaced offset of (6) with (7 - weekstart)
var dayNr = (this.getDay() + 7 - weekstart) % 7;
target.setDate(target.getDate() - dayNr + 0);//0 means friday
var firstDay = target.valueOf();
target.setMonth(0, 1);
if (target.getDay() !== 4) {
target.setMonth(0, 1 + ((4 - target.getDay()) + 7) % 7);
}
return 1 + Math.ceil((firstDay - target) / 604800000);;
};
//get date rance of week
Date.prototype.getDateRangeOfWeek = function (weekNo, weekstart) {
var d1 = this;
var firstDayOfWeek = eval(d1.getDay() - weekstart);
d1.setDate(d1.getDate() - firstDayOfWeek);
var weekNoToday = d1.getWeekNumber(weekstart);
var weeksInTheFuture = eval(weekNo - weekNoToday);
var date1 = angular.copy(d1);
date1.setDate(date1.getDate() + eval(7 * weeksInTheFuture));
if (d1.getFullYear() === date1.getFullYear()) {
d1.setDate(d1.getDate() + eval(7 * weeksInTheFuture));
}
var rangeIsFrom = eval(d1.getMonth() + 1) + "/" + d1.getDate() + "/" + d1.getFullYear();
d1.setDate(d1.getDate() + 6);
var rangeIsTo = eval(d1.getMonth() + 1) + "/" + d1.getDate() + "/" + d1.getFullYear();
return { startDate: rangeIsFrom, endDate: rangeIsTo }
};
Your code can be look like this
var startdate = '01-08-2017'
var weekList = [];
var year = startdate.getFullYear();
var onejan = new Date(year, 0, 1);//first january is the first week of the year
var weekstart = onejan.getDay();
weekNumber = startdate.getWeekNumber(weekstart);
//generate week number
var wkNumber = weekNumber;
var weekDateRange = onejan.getDateRangeOfWeek(wkNumber, weekstart);
var wk = {
value: wkNumber
, text: 'Week' + wkNumber.toString()
, weekStartDate: new Date(weekDateRange.startDate)
, weekEndDate: new Date(weekDateRange.endDate)
};
weekList.push(wk);
I guess there is no directive or filter for this, you need to create one for yourself. you can refer date object from date-time-object

Pikaday date range don't work

I used the range function from pikaday.
with onSelectI set the date range what actually works.
Here is my example:
onSelect: function(date) {
var first_ = (date.getDate() - date.getDay())+1;
var last_ = first_ + 4;
var firstday = new Date(date.setDate(first_));
var lastday = new Date(date.setDate(last_));
picker.setStartRange(firstday);
picker.setEndRange(lastday);
picker.draw();
var f_startdate = firstday.getDate()+'.'+(firstday.getMonth()+1)+'.'+firstday.getFullYear();
var f_enddate = lastday.getDate()+'.'+(lastday.getMonth()+1)+'.'+lastday.getFullYear();
var kw = getWeekNumber(date.getFullYear()+'/'+(date.getMonth()+1)+'/'+date.getDate());
document.getElementById('calendar').value = f_startdate+' - '+f_enddate;
// document.getElementById('calendar').value = 'KW: '+(kw+1);
}
But when I select the 03.06.2016 the range is set to the "30.05.2016 - 03.05.2016" and the Input is wrong. Maybe anyone can help me.
Here is a working example: https://jsfiddle.net/24aL9f21/1/
Your issue is here:
var first_ = (date.getDate() - date.getDay())+1;
That gives you the date of the previous Monday, but also goes negative. 3 June is a Friday (day number 5), so first_ is set to:
3 - 5 + 1 = -1
Then:
var last_ = first_ + 4;
so last_ is set to 3. Now when you do:
var firstday = new Date(date.setDate(first_));
you are actually setting date to a date of -1, which is one before the start of the month so 30 May. setDate returns the time value, so firstday is a new Date instance set to 30 May also.
Then:
var lastday = new Date(date.setDate(last_));
you are setting date to 3 May (remembering that in the line above you set it to 30 May). Again, the setDate method returns the time value, so a new Date object is created for that date. So you get dates for 30 May and 3 May (and if you check date, you'll set it's also 3 May).
QED (which my Mathematics teacher told me was "Quite Easily Done"). ;-)
So your code for the Monday is fine. If you want to get the date for the following Friday, just do:
var lastday = date.setDate(date.getDate() + 4);
Here lastday and date will reference the same Date object, but creating another copy doesn't seem useful.

how to convert days to month in js?

This is my code:
var date1 = '01/02/2017';
var date2 = '31/01/2020';
var startDate = new Date( date1.split("/")[2], date1.split("/")[1]-1, date1.split("/")[0] );
var endDate = new Date( date2.split("/")[2], date2.split("/")[1]-1, date2.split("/")[0] );
var diff = new Date(endDate - startDate);
var diffResult = ((diff.getFullYear() - 1970) * 12+ diff.getMonth()) + " months";
so the output is only 35 months (and also 30 days but its hidden)
but as 30 days are actually already a month, I would like to have it as 36 months.
any suggestions?
thanks
There are several good thoughts/solutions in the comments. It seems what you're really after is the number of 30-day intervals that fit between the start and end date.
After all, 30 days is not always a month as months can have 31 days.
If you're interested in how many 30-day intervals fit between a start and end date you can count the days and divide by 30:
var date1 = '01/02/2017';
var date2 = '31/01/2020';
var dateRegex = /\d+/g;
var date1Array = date1.match(dateRegex);
var date2Array = date2.match(dateRegex);
var startDate = new Date(date1Array[2], date1Array[1], date1Array[0]);
var endDate = new Date(date2Array[2], date2Array[1], date2Array[0]);
var diffResult = Math.round((endDate-startDate)/(1000*60*60*24));
var months = Math.floor(diffResult/30);
alert(months);
Credit for the equation to get the number of days goes to this question.

Categories