I have the following code to ensure that if the user selects the same check in date as check out date for the conference, then the "total_days" = 1
if the difference in dates is > 0 - then it is supposed to update one more day for each one. ie "conference date in = 13.06.12" "conference date out = 13.06.12" - total days = 1 - this is correct. however, if "conference date in = 13.06.12", and "conference date out = 14.06.12", then "total_days" needs to be 2, instead of 1. what am I doing wrong? I have tried the following:
<td>Conference Date In</td>
<td><input type="text" name="conference_date_in" id="conference_date_in" class="datepicker" /></td>
<td> </td>
<td>Conference Date Out</td>
<td><input type="text" name="conference_date_out" id="conference_date_out" class="datepicker" /></td>
</tr>
<td>Total Days</td>
<td><input type="text" name="total_days" id="total_days" /></td>
</tr>
<script type="text/javascript">
$(function() {
$(".datepicker").datepicker({ minDate: -0, maxDate: "+100M +10D",dateFormat: 'dd-mm-yy'})
({
changeMonth: true,
changeYear: true,
});
});
var enquiry_date = $.datepicker.formatDate('dd-mm-yy', new Date());
document.getElementById('enquiry_date').value = enquiry_date;
var calcDate = function() {
var start = $('#conference_date_in').datepicker('getDate');
var end = $('#conference_date_out').datepicker('getDate');
var days = (end - start) / 1000 / 60 / 60 / 24;
if(days==0) {days=1
}
if( days >= 0 ) {
document.getElementById('total_days').value = days;
}
}
$('#conference_date_out').change(calcDate);
$('#conference_date_in').change(calcDate);
Posting this ass answer to close the issue.
Can't you just add 1 to the result of (end - start) / 1000 / 60 / 60 / 24;?
You have to if's not if..else so this should resolve your issue.
Related
I am creating a scheduled delivery system.
I put together the following script that counts the quantity of specific days of the week between two dates in dd/mm/yyyy format (UK).
var date0 = "01/02/2021";
var date1 = "31/01/2022";
var dayList = [1]; // Monday based on Sunday being 0
var test = countDays(dayList,parseDate(date0),parseDate(date1));
alert(test);
function parseDate(str) {
var dmy = str.split('/');
return new Date(+dmy[2],dmy[1] - 1,+dmy[0]);
}
function countDays(days,fromDate,toDate) {
var ndays = 1 + Math.round((toDate-fromDate)/(24*3600*1000));
var sum = function(a,b) {
return a + Math.floor((ndays+(fromDate.getDay()+6-b)%7)/7);
};
return days.reduce(sum,0);
}
I this particular instance the dayList=[1] is 'Monday'. The script counts the number of Monday's between the two dates and we get the result 53 (because it happens that 01/02/2021 falls on a Monday).
This would works great if I want to find out how many Mondays were between two dates based on a rolling week.
How can I modify this to allow for a rolling fortnight?
For example I might want to find out how many weekly Mondays and alternate Fridays there are based on a rolling fortnight, not a rolling week. I have to allow for a mixture of weekly and fortnightly deliveries.
For example:
In this case the client wants a delivery every Monday and an extra delivery every other Friday.
Sat Sun Mon Tue Wed Thu Fri Sat Sun Mon Tue Wed Thu Fri
x x x
Schedules vary enormously. The rolling fortnight starts on the start date provided by the user.
What I am looking for is the total number of days between a start and end date but I am struggling with factoring the 'rolling fortnight' aspect of this.
This is the solution I came up with. I am sure that this can be expanded further but I have the ability to store an array of the delivery dates and (now that I have the total number of deliveries) I can calculate costs based on other information.
I hope this is of help.
function parseDate(str) {
//handles the dd/mm/yyyy format UK date
var dmy = str.split('/');
return new Date(+dmy[2], dmy[1] - 1, + dmy[0]);
}
var fromDate = parseDate(document.getElementById("startdate").value); // convert the date to js date
var toDate = parseDate(document.getElementById("enddate").value); // convert the date to js date
var thisDay = fromDate.getDay();
var thisWeek;
var thisValue;
var testWeek;
var testElement;
var result = 0;
while (fromDate <= toDate) {
if (thisDay >= 14) {
thisDay = 1;
}
thisWeek = Math.ceil(thisDay / 7);
for (i = 1; i <= 14; i++) {
testElement = document.getElementById("day" + i);
testWeek = Math.ceil(i / 7);
if ((testElement.checked) && (thisDay == i) && (thisWeek == testWeek)) {
result++;
}
}
thisDay++;
fromDate.setDate(fromDate.getDate() + 1);
}
alert("Number of deliveries is: " + result);
<input name="startdate" id="startdate" type="text" value="01/02/2021"/>
<input name="enddate" id="enddate" type="text" value="14/05/2021"/>
<table>
<thead>
<tr>
<th>Mon</th>
<th>Tue</th>
<th>Wed</th>
<th>Thu</th>
<th>Fri</th>
<th>Sat</th>
<th>Sun</th>
<th>Mon</th>
<th>Tue</th>
<th>Wed</th>
<th>Thu</th>
<th>Fri</th>
<th>Sat</th>
<th>Sun</th>
</tr>
</thead>
<tbody>
<tr>
<td><input class="tick checkboxgroup" type="checkbox" name="day1" id="day1" checked="checked"/></td>
<td><input class="tick checkboxgroup" type="checkbox" name="day2" id="day2"/></td>
<td><input class="tick checkboxgroup" type="checkbox" name="day3" id="day3"/></td>
<td><input class="tick checkboxgroup" type="checkbox" name="day4" id="day4"/></td>
<td><input class="tick checkboxgroup" type="checkbox" name="day5" id="day5"/></td>
<td><input class="tick checkboxgroup" type="checkbox" name="day6" id="day6"/></td>
<td><input class="tick checkboxgroup" type="checkbox" name="day7" id="day7"/></td>
<td><input class="tick checkboxgroup" type="checkbox" name="day8" id="day8" checked="checked"/></td>
<td><input class="tick checkboxgroup" type="checkbox" name="day9" id="day9"/></td>
<td><input class="tick checkboxgroup" type="checkbox" name="day10" id="day10"/></td>
<td><input class="tick checkboxgroup" type="checkbox" name="day11" id="day11"/></td>
<td><input class="tick checkboxgroup" type="checkbox" name="day12" id="day12" checked="checked"/></td>
<td><input class="tick checkboxgroup" type="checkbox" name="day13" id="day13"/></td>
<td><input class="tick checkboxgroup" type="checkbox" name="day14" id="day14"/></td>
</tr>
</tbody>
</table>
I think you could get the day names between the dates, and then use a reduce to count how many times each appears, and then use that to calculate how many deliveries there are:
const start = new Date('2022-11-17T03:24:00');
const endDate = new Date('2022-12-31T03:24:00');
const getDaysBetweenDates = function*(s, e) {
let currentDate = s;
while (currentDate < e) {
yield currentDate.toLocaleDateString("en-us", { weekday: 'long' });
currentDate = new Date(currentDate.getTime() + (24 * 60 * 60 * 1000));
}
}
const dayCounts = Array.from(getDaysBetweenDates(start, endDate))
.reduce((p, c) => ({
...p,
[c]: (p.hasOwnProperty(c) ? p[c] + 1 : 1)
}), {});
console.log(dayCounts.Monday + Math.floor(dayCounts.Friday / 2));
I want to restrict date for fifteen days only, I have written some code but don't know where I am going wrong. If anyone can guide me it would be helpful.
this is my full code, I am applying condition also to check if date is greater then 15 but it's not working
<body>
<form>
<div class="container">
<h4>Start Date:</h4>
<input type="text" id="startdate" name="fromdate" width="276"
placeholder="dd/mm/yyyy" required onchange="checkDate()" />
<h4>End Date:</h4>
<input type="text" id="enddate" name="todate" width="276"
placeholder="dd/mm/yyyy" required onchange="checkDate()"/>
</div>
<input type="submit" value="submit">
</form>
<script>
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();
}
});
//function to check wether date is more than 15 its not workin
//all plugins are there u just have to run
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 > 15){
alert("Days are more then fifteen");
}
}
</script>
</body>
</html>
here is the fiddle
It's because your datepicker has format dd/mm/yyyy but Date constructor converts it as if it was mm/dd/yyyy.
var date = '01/03/2018'
var d = new Date(date);
console.log(d.toString())
You need to adapt your code to work with dd/mm/yyyy format
function checkDate(start, end){
//convert strings to date for comparing
var startDate = createDate(start);
var endDate = createDate(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 > 15){
console.log("Days are more then fifteen");
} else {
console.log("Less than 15 days")
}
}
function createDate(datestr){
var datearr = datestr.split("/");
var d = new Date(datearr[2], Number(datearr[1]) - 1, datearr[0])
return d;
}
checkDate("01/02/2018", "10/02/2018")
checkDate("01/02/2018", "30/02/2018")
jsfiddle
The issue is with the date format you're using. 'dd/mm/yyyy' is not a format Date.parse() can handle.
String value representing a date. The string should be in a format
recognized by the Date.parse() method
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#Parameters
So you can either change the format to 'mm/dd/yyyy' or you can use moment.js to handle your date manipulations.
If you prefer to stick with the same format and Date library, then you have a solution here
PS: I noticed you have asked the same question before and having issues with the accepted answer. When this happens, please comment on the answer instead of making a duplicate
Look at this answer, here I have used a moment.js library also. this will restrict to 15 days. Hope this sample will give you a solution
$(document).ready(function(){
$('#date-of-ending').datepicker({
autoclose: true,
format:"dd/mm/yyyy"
})
$('#date-of-starting').datepicker({
autoclose: true,
format:"dd/mm/yyyy"
}).on('changeDate', function (selected) {
var xDays = 15;
var selectedDate = moment(selected.date,"DD/MM/YYYY").format("MM/DD/YYYY")
var maxDate = moment(selectedDate.valueOf()).add(xDays, 'days').format('DD/MM/YYYY'); // This is from moment js library
$('#date-of-ending').datepicker('setEndDate', maxDate);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.8.0/js/bootstrap-datepicker.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.8.0/css/bootstrap-datepicker.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
<input id="date-of-starting" type="text" name="startDate" value="" readonly class="form-control" required />
<input id="date-of-ending" type="text" name="endDate" value="" readonly class="form-control" required />
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>
This question already has answers here:
How to calculate number of days between two dates?
(42 answers)
Closed 6 years ago.
I'm making simple application for record internal leaves of my office. with this application I have to provide users to two HTML date fields for select start leave date and end leave date. At the same time I need to calculate how many days have in between user's selection also this count may exclude the weekdays. To do this i tried to use simple javascript with one of date fields onchange event but it's not working
this is the complete code with HTML I have tried
<html >
<head>
</head>
<body>
<form action='reqprocess.php' method='post'>
<td><input type="date" name="datepicker" class='form-control' id="startd" required/> <br>
<td><input type="date" name="datepicker2" class='form-control' id="endd"required /> <br>
<td><input type="text" name='leavehmd' class='form-control' id="lhmd"/><br>
<input type='submit' value='Apply' class='btn btn-primary' />
</form>
<script type="text/javascript">
var chng1 = document.getElementById("endd");
chng1.onchange = function () {
var date1 = Date.parse(document.getElementById("startd").value);
var date2 = Date.parse(document.getElementById("endd").value);
if (date1 && date2) {
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
//alert(diffDays);
document.getElementById("lhmd").value = diffDays;
}
}
var chng2 = document.getElementById("startd")
chng2.onchange = function () {
var date1 = Date.parse(document.getElementById("startd").value);
var date2 = Date.parse(document.getElementById("endd").value);
if (date1 && date2) {
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
//alert(diffDays);
document.getElementById("lhmd").value = diffDays;
}
}
</script>
</body>
</html>
But when sect second date, on-change function not works and Input field suppose to fill with counted dates not populated. How can I fix this ?
or how can I achieve this via methods like ajax or jquery
You need to make sure there is a value in each input field before attempting to calculate the difference
You can check this by setting a conditional with the values as the operands. They will evaluate to falsy if there is no value and truthy if there is a value. If both values are present, you can then calculate the difference.
The linked duplicate question has a good clean way to count days between dates:
function parseDate(str) {
var mdy = str.split('/');
return new Date(mdy[2], mdy[0]-1, mdy[1]);
}
function daydiff(first, second) {
return Math.round((second-first)/(1000*60*60*24));
}
var chng1 = document.getElementById("endd");
var chng2 = document.getElementById("startd");
chng1.onchange = displayCurrentDayDifference();
chng2.onchange = displayCurrentDayDifference();
function displayCurrentDayDifference() {
var date1 = document.getElementById("startd").value;
var date2 = document.getElementById("endd").value;
if (date1 && date2) {
var daysBetween = daydiff(parseDate($('#startd').val()), parseDate($('#endd').val()));
document.getElementById("lhmd").value = daysBetween;
}
}
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" />