Get the total days from datepicker - javascript

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

Related

Jquery is getting the incorrect difference between now and a future date

I tried to code a counter. For the first value it should show the difference between today and a future date. Out of some reason its showing an complete wrong difference. Do you know why?
The set future date 2th october 2020 should output a difference of 15 days and not over 40.
const oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds
const firstDate = new Date(2020, 10, 02);
const secondDate = new Date();
const diffDays = Math.round(Math.abs((firstDate - secondDate) / oneDay));
jQuery('#reducedaily').text(diffDays);
jQuery('.count, .count2').each(function () {
jQuery(this).prop('Counter',0).animate({
Counter: jQuery(this).text()
}, {
duration: 4000,
easing: 'swing',
step: function (now) {
if(jQuery(this).hasClass('count')){
jQuery(this).text(now.toFixed(0));
}
else{
jQuery(this).text(now.toFixed(1));
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<div id="counterbackground" class="shadow">
<div class="counterdiv"><span class="count countervalue" id="reducedaily">239</span><br> <span class="counterdescription">Tage bis zum Event<br> (2.10.2020)</span></div>
</div>
When using the "month" parameter in the Date function in your jQuery, months are 0-indexed so they start at 0 instead of 1 as you might expect. So when you pass in 10, that actually represents November instead of October - this is why you got 30 extra days than you expected.
There are many ways to specify the date (see MDN Web Docs for Date). For example any of these will create a date object for 02 October 2020:
firstDate = new Date(2020, 09, 02); // when using the month param, it is (month-1)
firstDate = new Date("2020-10-02"); // note you DO use "10" in a date string
firstDate = new Date("10/02/2020"); // note mm/dd/yyyy format
firstDate = new Date("2 October 2020"); // or you can use text
Working Example with your code
const oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds
const firstDate = new Date(2020, 09, 02);
const secondDate = new Date();
const diffDays = Math.round(Math.abs((firstDate - secondDate) / oneDay));
jQuery('#reducedaily').text(diffDays);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<div class="counterdiv"><span class="count countervalue" id="reducedaily">239</span><br> <span class="counterdescription">Tage bis zum Event<br>(2.10.2020)</span></div>
Working Example to test date strings
const oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds
const secondDate = new Date();
$("#testdate").on("click", function() {
dateStr = $("#date_to_check").val();
showDate(dateStr, "days_left");
});
showDate("2020-10-02", "days_left_test");
showDate("10/02/2020", "days_left_test");
showDate("2 October 2020", "days_left_test");
showDate("October 02 2020", "days_left_test");
function showDate(dateStr, elid){
document.getElementById(elid).innerHTML += "Date: <b>"+dateStr+" </b> Days left: <b>"+ Math.round(Math.abs((new Date(dateStr) - secondDate) / oneDay))+"</b><br>";
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<p>Test a date:</p>
<input type="text" id="date_to_check" placeholder="Enter date string">
<button id="testdate">Test</button>
<div id="days_left" style="margin-bottom: 20px"></div>
<p><b>More date Tests:</b></p>
<div id="days_left_test"></div>

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

Date days gap should not me more then 20 days

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>

How to calculate age from jquery datepicker?

I want to calculate age when date is selected by using jquery date picker. I added code below but it showing minus value if i select date like '19/03/2015','15/01/2015' or '19/03/2014' ,'31/12/2014'
$(document).ready(function ()
{
console.log($(document).width());
$('#patientDob').datepicker
({
dateFormat: 'dd/mm/yy',
changeMonth: true,
changeYear: true,
yearRange: '1900:2150',
maxDate: new Date(),
inline: true,
onSelect: function() {
var birthDay = document.getElementById("patientDob").value;
var DOB = new Date(birthDay);
var today = new Date();
var age = today.getTime() - DOB.getTime();
age = Math.floor(age / (1000 * 60 * 60 * 24 * 365.25));
document.getElementById('patientAge').value = age;
}
});
});
I have created this age calculator for my project
using jQuery UI. and JavaScript function. you will get the exact result.
It it will calculate age and display as human readable.
create a date field with ID 'datepicker'and import jquery and jquery ui . After that
Then just copy and paste the code to get the exact result.
output // 28 years 7 months 7 days
$(function () {
$("#datepicker").datepicker({
changeMonth: true,
changeYear: true,
showAnim: 'slideDown',
dateFormat: 'yy-mm-dd'
}).on('change', function () {
var age = getAge(this);
/* $('#age').val(age);*/
console.log(age);
alert(age);
});
function getAge(dateVal) {
var
birthday = new Date(dateVal.value),
today = new Date(),
ageInMilliseconds = new Date(today - birthday),
years = ageInMilliseconds / (24 * 60 * 60 * 1000 * 365.25 ),
months = 12 * (years % 1),
days = Math.floor(30 * (months % 1));
return Math.floor(years) + ' years ' + Math.floor(months) + ' months ' + days + ' days';
}
});
AFAIK The javascript Date requires yyyy/mm/dd, and you are sending:
var DOB = new Date(birthDay); // dateFormat: 'dd/mm/yy'
Change format to "yyyy/mm/dd" and will work ok.

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.

Categories

Resources