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;
}
}
Related
how to get number of days between two dates but its not working i think my date format not correct but how to change date format and get number of days
$scope.ChangeDate = function () {
var oneDay = 24 * 60 * 60 * 1000;
var firstDate = $scope.Current.PlainnedStart;
var secondDate = $scope.Current.PlainnedEnd;
if (!angular.isUndefined(firstDate) && !angular.isUndefined(secondDate)) {
var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime()) / (oneDay)));
alert(diffDays);
$scope.Current.NOD = ++diffDays;
}
}
enter image description here
<input type="text" onchange="angular.element(this).scope().ChangeDate()"
id="date" ng-model="Current.PlainnedStart"
class="floating-label mdl-textfield__input" placeholder="">
you can use
<input class="form-control" ng-model="day1" ng-blur="getDate(day1)" type="text" readonly />
$scope.getDate= function (date) {
var dates = new Date();
console.log(dates);
}
you can easily manage with momentjs with date evens
var a = moment('2018-04-17T07:00:00.000Z');
var b = moment('2018-04-27T07:00:00.000Z');
var days = b.diff(a, 'days');
http://momentjs.com/
or with Javascript
var a = new Date("2018-04-17T07:00:00.000Z");
var b = new Date("2018-04-27T07:00:00.000Z");
var dayDif = (a - b) / 1000 / 60 / 60 / 24;
You should convert both dates into the JavaScript Date object. From what I can see, the inputs from both date inputs are in 'dd-mm-yyyy' format, and this will cause some problems if you try to directly convert it into the Date object. Instead, you should convert it to 'yyyy-mm-dd' before converting it to a date object.
Then, you can calculate the difference between both dates.
const str1 = '17-04-2019';
const str2 = '20-04-2019';
const toDate = dateStr => {
const parts = dateStr.split('-');
return new Date(parts[2], parts[1] - 1, parts[0]);
}
const diff = Math.floor((toDate(str2) - toDate(str1) ) / 86400000);
console.log(diff)
As mentioned in the previous answer above you can either split the string to get the values. Or change it like below
Ex:Suppose my date string is
var str1 = '17-Apr-2019';
var str2 = '20-Apr-2019';
var diff = Math.abs(new Date(str2).getDate() - new Date(str1).getDate());
console.log(diff)
Output => 3
Or if you dont want any code changes.
Change the format of the datepicker to (mm-dd-yyyy) you will get same output
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);
I have a start-date and end-date and I want to calculate array of dates between these days based on a given duration.
for example,
if start date is 01/01/2015 and end date is 01/06/2015 and if I give duration as 3 months then out put should be:
01/04/2015
01/06/2015
How to achieve this using JavaScript and I need to display it in a form.
If you want to calculate difference between two dates using javascript:
Then,
function dateDiff() {
var dtFrom = document.getElementById('txtFromDate').value;
var dtTo = document.getElementById('txtToDate').value;
var dt1 = new Date(dtFrom);
var dt2 = new Date(dtTo);
var diff = dt2.getTime() - dt1.getTime();
var days = diff/(1000 * 60 * 60 * 24);
alert(dt1 + ", " + dt2);
alert(days);
return false;
}
function isNumeric(val) {
var ret = parseInt(val);
}
HTML:
<label for="txtFromDate">From Date : </label>
<input type="text" id="txtFromDate" name="txtFromDate" size="10" maxlength="10" value="03/25/2013"/><br/>
<label for="txtToDate">To Date : </label>
<input type="text" id="txtToDate" name="txtDate" size="10" maxlength="10" value="03/26/2013"/><br/>
<button id="btnCheck" name="btnCheck" onClick="dateDiff();" type="button">Difference</button>
AFTER EDIT:
Following solution is to get all dates between specified dates.
Working Demo
// using Datepicker value example code
$('#getBetween').on('click', function () {
var start = $("#from").datepicker("getDate"),
end = $("#to").datepicker("getDate");
var between = getDates(start, end);
$('#results').html(between.join('<br> '));
});
// This function doing this work.
function getDates(start, end) {
var datesArray = [];
var startDate = new Date(start);
while (startDate <= end) {
datesArray.push(new Date(startDate));
startDate.setDate(startDate.getDate() + 1);
}
return datesArray;
}
I have an input text that has a combination of date and time and display like this
04/01/2015 8:48PM
How can i convert this string to a date using the function new Date() in javascript? not output is shown
Here is what i've tried so far, i can only convert the date not the time.
HTML
<form name="frm1" >
<h3>Check in Date:</h3>
<input type="text" value="" class="datetimepicker_mask" name="dtp1" /><br><br>
<h3>Check out Date:</h3>
<input type="text" value="" class="datetimepicker_mask" name="dtp2" /><br><br>
<input type="button" onclick="computeDate()" value="Compute Difference" />
<br><b>No of days: </b>
<span id="date_difference"></span>
</form>
JAVSCRIPT
function computeDate() {
var dateTime1 = document.frm1.dtp1.value;
var dateTime2 = document.frm1.dtp2.value;
var startDate = new Date(dateTime1);
var endDate = new Date(dateTime2);
var timeDiff = Math.abs(endDate.getTime() - startDate.getTime());
if (timeDiff == 0) {
timeDiff = 1;
}
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
var total = parseFloat(diffDays) * parseFloat(roomRate);
document.getElementById("date_difference").innerHTML = diffDays;
document.getElementById("date_difference").style.visibility = "visible";
}
If the date format is always the same, create a convience function that converts the date to a Date object
function convert(date) {
var dateArr = date.split(/[\s\/\:]/);
if (dateArr[4].toLowerCase().indexOf('pm') != -1)
dateArr[3] = (+dateArr[3]) + 12;
dateArr[4] = dateArr[4].replace(/\D/g,'');
dateArr[0]--;
return new Date(dateArr[2], dateArr[0], dateArr[1], dateArr[3], dateArr[4]);
}
FIDDLE
Here is an answer that will both solve this and make development easier. This suggestion will require an extra library for addressing such issues as you are having here- time, but you'll likely find it beneficial when working with JavaScript dates in general. It already looks like you're writing manual date functions. Abstract them away with robust libraries for solving these same issues that have come up again and again. Using date.js, here is how easy this becomes
Date.parse('04/01/2015 8:48PM ')
JSFiddle Example
You can create the Date object after parsing the dateString
var d = new Date(year, month, day, hours, minutes, seconds, milliseconds);
you can use the parseDate function as following
var testDate = "04/01/2015 8:48PM";
console.log(parseDate(testDate));
function parseDate(dateStr){
var dateTime = dateStr.split(/\/| |:|(?=[PA])/);
for(var i=0; i<5; i++){
dateTime[i] = parseInt(dateTime[i]);
}
if(dateTime[5] == "PM"){
dateTime[3] += 12;
}
return new Date(dateTime[2], dateTime[1], dateTime[0], dateTime[3], dateTime[4]);
}
Try it at JSFiddle
The requirement is I have two date fields:
One is effective date and date of birth. When I select the effective date on the page.
The age field should do the following calculation.
That is age would be Effective date - date of birth. the result should be set to the age field.
How to do in javascript or JQuery?
I'm using tapestry front end. So in the HTML page I want to do this setting of value to age field.
You need to convert your dates into milliseconds and subtract them, then calculate the age.
HTML
<input type="date" id="effective" />
<input type="date" id="born" />
jQuery
function getTime(date){
var dateArr = date.split('-');
return new Date(dateArr[0], dateArr[1], dateArr[2]).getTime();
}
function calcDate(date1,date2) {
var eff_date = getTime(date1);
var born_date = getTime(date2);
var diff = Math.floor(eff_date - born_date);
var day = 1000* 60 * 60 * 24;
var days = Math.floor(diff/day);
var months = Math.floor(days/31);
var years = Math.floor(months/12);
return years
}
$("input[type=date]").change(function(){
if($("#effective").val() != "" && $("#born").val() != ""){
var age = calcDate($("#effective").val(),$("#born").val())
alert(age);
}
});
Check out this Fiddle..