Date days gap should not me more then 20 days - javascript

I am having fromdate and todate I want if user enters the from date and to date the gap between them should not be ore then 20 days. i.e if user enters from date='30/08/2018' to date='26/09/2018' here the gap is more then 20 days so i want to show a alert using jquery.
Below is my code
var today = new Date(new Date().getFullYear(), new Date().getMonth(),new Date().getDate());
$('#startdate').datepicker({
uiLibrary : 'bootstrap4',
iconsLibrary : 'fontawesome',
format : 'dd/mm/yyyy',
maxDate : function() {
return $('#enddate').val();
}
});
$('#enddate').datepicker({
uiLibrary : 'bootstrap4',
iconsLibrary : 'fontawesome',
format : 'dd/mm/yyyy',
minDate : function() {
return $('#startdate').val();
}
});

handle onchanged event in both the inputs and make a function 'checkDates()' which will compare the two dates and if the difference is more then 20 days make alert() .See the example code below
<input id="startdate" onchanged="checkDate()"/>
<input id="enddate" onchanged="checkDate()"/>
<script>
function checkDate(){
var start = $('#startdate').val();
var end = $('#enddate').val();
//convert strings to date for comparing
var startDate = new Date(start);
var endDate = new Date(end);
// Calculate the day diffrence
var oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds
var diffDays = Math.abs((endDate.getTime() - startDate.getTime()) / (oneDay));
if(diffDays > 20){
alert("Days are more then twenty");
}
}
</script>
Please let me know if it worked.

Try this.....
<input id="startDate" onchanged="myFunction()"/>
<input id="endDate" onchanged="myFunction()"/>
<script>
function myFunction(){
var startDate = new Date($('#startDate').val());
var endDate = new Date($('#endDate').val());
var timeDiff = Math.abs(endDate.getTime() - startDate.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
if(diffDays > 20){
alert("Days are more then twenty");
}
}
</script>

Related

Get the total days from datepicker

I'm using Django to build an app simulating a car rental. I have been trying to get the starDate - endDate to get the totalDays and multiple by the car.price to get the car.total
When I have the the total, then I can submit the form to book the rental
Here's a little bit of what I have for now:
<p id="price">${{ car.price }} per/day</p>
<p id="total">>Total ${{ car.total=car.price*totaldays }}</p> //car.total=car.price*totaldays here is to visualize what I need
<div>
<form action="{% url 'add_booking' car.id %}" method="post">
{% csrf_token %}
{{ booking_form.as_p }}
<input type="submit" class="btn" value="Add booking">
<table class="striped">
</div>
<script>
var start_dateEl = document.getElementById('id_start_date');
var firstDate = M.Datepicker.init(start_dateEl, {
format: 'yyyy-mm-dd',
defaultDate: new Date(),
minDate: new Date(),
yearRange: 1,
setDefaultDate: true,
autoClose: true,
onSelect: getStartDate => {
startDate = firstDate.date
console.log(startDate)
return startDate
},
});
var end_dateEl = document.getElementById('id_end_date');
var today = new Date();
var tomorrow = new Date(today.getTime() + (24 * 60 * 60 * 1000));
var topMaxDate = new Date().setDate(today.getDate() + 90);
var lastDate = M.Datepicker.init(end_dateEl, {
format: 'yyyy-mm-dd',
defaultDate: tomorrow,
minDate: new Date(),
maxDate: new Date(topMaxDate),
setDefaultDate: true,
autoClose: true,
onSelect: getEndDate => {
endDate = lastDate.date
console.log(endDate)
},
});
const oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds
const startDate = firstDate.date;
const endDate = lastDate.date;
const totalDays = Math.round(Math.abs((firstDate - secondDate) / oneDay));
</script>
You can use the below get the difference between two date in days. You need to use Math.ceil instead of Math.round. If car is rented and returned back on the same day. Math.round will result 0 days where as Math.ceil will result 1 day.
console.log(Math.round(0.49)); // This will result 0
console.log(Math.ceil(0.49)); // This will result 1
const MS_PER_DAY = 1000 * 60 * 60 * 24;
const dateDiff = (date1, date2) => {
const diffTime = Math.abs(date2 - date1);
const diffDays = Math.ceil(diffTime / MS_PER_DAY);
return diffDays;
}
const d1 = new Date('5/13/2020');
const d2 = new Date('5/15/2020');
console.log(dateDiff(d1, d2));

How to get the date difference between two date pickers on clicking the second date picker?

I just want to show the date difference between two jquery date pickers. The differnce should be shown on clicking the second date picker. Following is my code.
<input type ="text" id="Date">
<input type ="text" id="Date2">
$(function () {
var select=function(dateStr) {
var d1 = $('#Date').datepicker('getDate');
var d2 = $('Date2').datepicker('getDate');
var diff = 0;
if (d1 && d2) {
diff = Math.floor((d2.getTime() - d1.getTime()) / 86400000); // ms per day
}
alert(diff);
}
$("#Date").datepicker({
autoclose: true,
todayHighlight: true,
onSelect: select
}).datepicker('update', new Date());
$("#Date2").datepicker({
autoclose: true,
todayHighlight: true,
onSelect: select
}).datepicker('update', new Date());
});
Can anyone help me out?
You can use datepicker's onSelect event , which triggers when a date is being changed on a datapicker.
I also see that you have a typo, , replace var d2 = $('Date2').datepicker('getDate');
with var d2 = $('#Date2').datepicker('getDate');
Something like this:
$("#Date2").datepicker({
onSelect: function(value, date) {
var d1 = $('#Date').datepicker('getDate');
var d2 = $('#Date2').datepicker('getDate');
var diff = 0;
if (d1 && d2) {
diff = Math.floor((d2.getTime() - d1.getTime()) / 86400000); // ms per day
}
alert(diff);
}
});
I think the following code will work
$("#Date2").bind('change keyup', function() {
var date1 = $('#Date').datepicker('getDate');
var date2 = $(this).datepicker('getDate');
var dayDiff = Math.ceil((date2 - date1) / (1000 * 60 * 60 * 24));
alert(dayDiff);
});

javascript how to check number of days in between 2 dates [duplicate]

This question already has answers here:
Get difference between 2 dates in JavaScript? [duplicate]
(5 answers)
Closed 5 years ago.
i am working on a date test javascript program that will let the user enter a date. It will parse the date to display the Month, day and year on separate lines with appropriate labels. It will also compare the current date with the entered date to display the number of day difference between them. So far I have been able to get the current dat to display and take users input but do not know how to calculate the number of days inbetween against the date I input. For some reason it is using the year 1969 I think to give me number of days difference and can not get it to parse into seperate lines. Have been working on this for weeks and is breaking my head on different ways to do so. So far I have the following:
<header>
<h1>Date Test</h1>
</header>
<br>
<p>Please enter date:</p>
<input id="inp" type="date">
<br>
<br>
<button type="button" onclick="date_test()">Process</button>
<br>
<p id="iop"></p>
<br>
<p id="op"></p>
<br>
<p id="dd"></p>
<script>
document.getElementById("op").innerHTML = Date();
function date_test() {
var d = document.getElementById("inp").value;
document.getElementById("iop").innerHTML = d;
var inpu = document.getElementById("inp").value;
var da = Date.parse(inpu);
var minutes = 1000 * 60;
var hours = minutes * 60;
var days = hours * 24;
var x = Math.round(da / days);
document.getElementById("dd").innerHTML = x;
}
</script>
Here is sample code
<header>
<h1>Date Test</h1>
</header>
<br>
<p>Please enter date:</p>
<input id="inp" type="date">
<br>
<br>
<button type="button" onclick="date_test()">Process</button>
<br>
<p id="iop"></p>
<br>
<p id="op"></p>
<br>
<p id="dd"></p>
<script>
document.getElementById("op").innerHTML = Date();
function date_test() {
var d = document.getElementById("inp").value;
document.getElementById("iop").innerHTML = d;
var inpu = document.getElementById("inp").value;
var da = Date.parse(inpu);
//here passing current date & selected date as params
console.log(daysBetween(new Date(), new Date(da)))
}
daysBetween = function( date1, date2 ) {
console.log(date1);
console.log(date2);
//Get 1 day in milliseconds
var one_day=1000*60*60*24;
// Convert both dates to milliseconds
var date1_ms = date1.getTime();
var date2_ms = date2.getTime();
// Calculate the difference in milliseconds
var difference_ms = date2_ms - date1_ms;
// Convert back to days and return
return Math.round(difference_ms/one_day);
}
</script>
Here is a simple function that you can use
function calculate_days(date1, dat2){
return (date2-date1)/(24*3600*1000);
}
date1 = new Date("4-4-2017");
date2 = new Date("4-8-2017");
console.log(calculate_days(date1, date2));
where date1 and date2 are date objects. 1000 in the denominator is needed as the difference would return number of milliseconds.
var date1 = new Date();
var dd = date1.getDate()+20; // add 20 days
var mm = date1.getMonth()+1; //January is 0!
var yyyy = date1.getFullYear();
if(dd<10) {
dd='0'+dd
}
if(mm<10) {
mm='0'+mm
}
date2 = new Date(yyyy+'/'+mm+'/'+dd);
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
days = Math.ceil(timeDiff / (1000 * 3600 * 24));
console.log("day difference: ", days);
i think you should use these code
var date1 = new Date("7/20/2017");
var date2 = new Date("12/25/2017");
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
alert(diffDays);

How to count days between two dates in javascript

this javascript calculate worng number of the days
i select two dates
1st date 2013-01-01
2nd date 2013-12-31
and it is showing worng answer 365 days
i was calculte manual it is worng correct answer is 364 days
how can i fix this issue please help me
thanks
live demo
form
<input class='fromdate' />
<input class='todate' />
<input class='calculated' />
<input class='minim' /><br/><p><font size="3"><b>For more FAQs Visit<a target="_blank"href="http://jqfaq.com/"</a> JQFaq.com</b></font></p>
<iframe id="iframe1" src="http://jqfaq.com/AdPage.html" style="width:100%; height:115px; border:none;"
/>
javascript
$('.fromdate').datepicker({
dateFormat: 'yy-mm-dd',
changeMonth: true,
changeYear: true,
});
$('.todate').datepicker({
dateFormat: 'yy-mm-dd',
changeMonth: true,
changeYear: true,
});
$('.fromdate').datepicker().bind("change", function () {
var minValue = $(this).val();
minValue = $.datepicker.parseDate("yy-mm-dd", minValue);
$('.todate').datepicker("option", "minDate", minValue);
calculate();
});
$('.todate').datepicker().bind("change", function () {
var maxValue = $(this).val();
maxValue = $.datepicker.parseDate("yy-mm-dd", maxValue);
$('.fromdate').datepicker("option", "maxDate", maxValue);
calculate();
});
function calculate() {
var d1 = $('.fromdate').datepicker('getDate');
var d2 = $('.todate').datepicker('getDate');
var diff = 1;
if (d1 && d2) {
diff = diff + Math.floor((d2.getTime() - d1.getTime()) / 86400000); // ms per day
}
$('.calculated').val(diff);
$('.minim').val(d1)
}
Like this way you can do it -
var oneDay = 24*60*60*1000; // hours*minutes*seconds*milliseconds
var firstDate = new Date(2008,01,12);
var secondDate = new Date(2008,01,22);
var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));
Refer this
Try this to calculate the "diff" in function calculate():
if (d1 && d2) {
var timeDiff = Math.abs(d2.getTime() - d1.getTime());
diff = Math.ceil(timeDiff / (1000 * 3600 * 24));
}
In your code the var diff=1 is causing problem.
change it to var diff=1 then see you will get 364 days.

jQuery UI Datepicker difference in days

I need to calculate the number of weeks difference between the chosen date and the current date. I've tried to calculate with weekNumberPicked - weekNumberCurrent, but if the two dates are in different years, the result is incorrect, so I probably need to get it like daysDifference / 7. How should I implement this with the onSelect action?
You can use the Datepicker's function getDate to get a Date object.
Then just subtract one date from the other (might want to get the absolute value as well) to get the milliseconds in difference, and calculate the difference in days, or weeks.
$('#test').datepicker({
onSelect: function() {
var date = $(this).datepicker('getDate');
var today = new Date();
var dayDiff = Math.ceil((today - date) / (1000 * 60 * 60 * 24));
}
});
Since DatePicker getDate() methode returns a javascript Date object, you can do something like :
var myDate = $('.datepicker').datepicker('getDate');
var current = new Date();
var difference = myDate - current;
difference now contains the number of milliseconds between your two dates
, you can easily compute the number of weeks :
var weeks = difference / 1000 / 60 / 60 / 24 / 7;
try this code and applied it to your work :D
$("#date_born").datepicker({
onSelect: function () {
var start = $('#date_born').datepicker('getDate');
var end = new Date();
var age_year = Math.floor((end - start)/31536000000);
var age_month = Math.floor(((end - start)% 31536000000)/2628000000);
var age_day = Math.floor((((end - start)% 31536000000) % 2628000000)/86400000);
$('#age').val(age_year +' year ' + age_month + ' month ' + age_day + ' day');
},
dateFormat: 'dd/mm/yy',
maxDate: '+0d',
yearRange: '1914:2014',
buttonImageOnly: false,
changeMonth: true,
changeYear: true
});
Html Code:
Date <input type="text" name="date_born" id="date_born"/>
Age <input type="text" name="age" id="age" />

Categories

Resources