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

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

Related

Calculate difference in days between a date pulled from an API and todays today

I am currently trying to figure out how to calculate the difference in days between a date pulled through from an API and today's date.
this is the code I have used to get todays date in the format that matches date from the API:
var today = new Date();
var dd = String(today.getDate()).padStart(2, '0');
var mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0!
var yyyy = today.getFullYear();
today = dd + '/' + mm + '/' + yyyy;
This twig code pulls the date of the API through
{{ job.date }}
What I need to work out to do and struggling with is
today - {{ job.date }} = Difference in Days
I have looked through the articles here but I have struggled to find one that I can understand.
Could this be done with twig?
Any help would be appreciated and even more so if someone could put the snippet together for me.
jQuery approach with help of this post
//split
var todayArr = ('11/03/2019').split('/');
var startDateArr = ('10/03/2019').split('/');
//change format
var today = `${todayArr[2]}-${todayArr[1]}-${todayArr[0]}`
var startDate = `${startDateArr[2]}-${startDateArr[1]}-${startDateArr[0]}`
//calculate
var diff = new Date(Date.parse(today) - Date.parse(startDate));
var days = diff/1000/60/60/24;
console.log(days);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
You can do something like this......
function countDays(firstDate, secondDate) {
var startDay = new Date(firstDate);
var endDay = new Date(secondDate);
var millisecondsPerDay = 1000 * 60 * 60 * 24;
var millisBetween = startDay.getTime() - endDay.getTime();
var days = millisBetween / millisecondsPerDay;
// Round down.
alert(Math.floor(days));
}
If your date from api is "06/10/18" in "dd/mm/yy" format then
let date = "06/10/18";
let values = date.split("/");
date = new Date("20"+values[2],values[1]-1,values[0]);//months are from 0 to 11
let currDate = new Date();
let diff = currDate.getTime() - date.getTime();
diff = diff/1000; // seconds
diff = diff/60; // minutes
diff = diff/60; // hours
diff = diff/24; //days
let days = Math.round(diff);

how to get number of days from angularjs

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

how to check time difference of two fields that use time pickers

I have two time pickers and I need to check if the time selected from start to end is within a correct range, i got the values difference checked, but the values returned is NaN. Time shown is as 8:00 PM to 10:00 PM etc.
<div class="col-md-2">
<label>Service Start</label>
<input class="form-control timepicker1" type="text" id="start_time" />
</div>
<div class="col-md-2">
<label>Service End</label>
<input class="form-control timepicker1" type="text" id="end_time" />
</div>
Likely not the best since handling times with AM and PM you need to do some more work, also you need to check if first_time < second_time.
What you do is convert hh:mm:ss in seconds than input seconds in new Date() and can get different outputs.
But it should give you an idea how it can be done. moment.js can make things a lot easier
var hm_1 = '09:00 PM';
var hm_2 = '12:00 PM';
var a = hm_1.split(/:| /); // split at : and " "
var b = hm_2.split(/:| /);
// convert hours and minutes into seconds
var sec_1 = a[0] * 60 * 60 + a[1] * 60;
var sec_2 = b[0] * 60 * 60 + b[1] * 60;
console.log("convert", hm_1, "and", hm_2, "in", "seconds", sec_1, sec_2);
var date = new Date();
var date = new Date((sec_2 - sec_1) * 1000); //use js new Date () can take s/h/... as input
var hh = date.getUTCHours(); //get hours
var mm = date.getUTCMinutes(); //get minutes
if (hh < 10) {hh = "0"+hh;}
if (mm < 10) {mm = "0"+mm;}
// convert to hh:mm (its a 24h format)
var timeString = hh+":"+mm;
console.log("result", timeString)

Count dates between two HTML Date input fields real time [duplicate]

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

Javascript: Subtract time with another fixed time

Consider I have following date and time in 24 hours format.
Example
2015/04/02 12:00
2015/03/02 14:00
I have to subtract the above time with 9 hours so that I will get
2015/04/02 -> 3 (hours)
2015/03/02 -> 5 (hours)
HTML
<form name="formName" onsubmit="return checkDate(this)">
<input type="text" value="" name="date1" />
<input type="text" value="" name="date2"/>
<input type="submit" value="Submit">
</form>
<p id="demo"></p>
Javascript
function checkDate(theForm)
{
var a = theForm.date1.value;
var b = theForm.date2.value;
var date1 = new Date(a);
var date2 = new Date(b);
var dateStart = new Date();
var dateEnd = new Date();
dateStart.setHours(9);
Start_sec = (date1/ 1000.0) - (dateStart/ 1000.0);
Start_hours = parseInt(Start_sec / 60 / 60);
document.getElementById("demo").innerHTML = Start_hours ;
return false;
}
Try the following code.
function checkDate(theForm)
{
var a = theForm.date1.value;
var b = theForm.date2.value;
var date1 = new Date(a);
var date2 = new Date(b);
date1.setHours(date1.getHours() - 9);
date2.setHours(date2.getHours() - 9);
document.getElementById("demo").innerHTML = "Date 1 : " + date1.toString() + "<br/>Date 2 : " + date2.toString();
return false;
}
If it is acceptable to use third party libraries, then you can achieve this task simply using moment.js. In one line, you can accomplish the task with this code:
moment('2015/04/02 12:00').subtract('hours',9).format('YYYY/MM/DD hh:mm')
//just a number plus the word 'hours'
.format('h [hours]')
//time only
.format('h:mm')
Occasionally I update this fiddle I maintain with more examples: http://jsfiddle.net/JamesWClark/9PAFg/
var date = new Date("2015/04/02 12:00");
var out = new Date(date.getTime() - 32400000); //9*60*60*1000
You can just literally subtract 9 hours directly...:
var t = new Date(2015,2,3,18);
t.setTime(t - 9*60*60*1000); //subtract 9 hours

Categories

Resources