Calculate workingdays between 2 days javascript [duplicate] - javascript

This question already has answers here:
exclude weekends in javascript date calculation
(6 answers)
Calculate working days between two dates in Javascript excepts holidays
(10 answers)
Closed 1 year ago.
I know this question is asked a lot of times. And i did my research, but i really don't understand it. I just started using javascript.
This is my code to calculate days between the two inputs.. I erased my attempts to calculate weekend.
function GetDays(){
var datefrom = new Date(document.getElementById("datefrom").value);
var dateto = new Date(document.getElementById("dateto").value);
return parseInt((dateto - datefrom) / (1000 * 60 * 60 * 24));
}
function cal(){
if(document.getElementById("dateto")){
document.getElementById("numdays2").innerHTML=GetDays();
}
}
An answer in PHP is also good for me.
Hope someone can help me.

You should really make your function with parameters, so that the function can be unaware of input/output details and does not have to reference document.
Also, it is a habit to start function names with a lowercase letter unless it is a constructor (which is not the case here).
As to the algorithm: move the two given dates to the Sunday that precedes them (unless they already are Sundays). As getDay() returns 0 for Sunday, you can just subtract the getDay() number of days from the date, and it will be a Sunday. Remember how many working days you subtracted like that.
Then when both dates are Sundays, calculate the number of weeks between them and multiply this by 5 (working days).
Finally adjust this number by adding and subtracting the days you altered the dates with in order to make them align with Sunday.
Here is an interactive snippet:
function getDays(datefrom, dateto) {
datefrom = new Date(datefrom);
dateto = new Date(dateto);
let before = datefrom.getDay();
datefrom.setDate(datefrom.getDate() - before); // Go to previous Sunday
if (before) before--; // should be in {0,1,2,3,4,5}
let after = dateto.getDay();
dateto.setDate(dateto.getDate() - after); // Go to previous Sunday
if (after == 6) after--; // should be in {0,1,2,3,4,5}
// Count each 7 day difference as 5 days, and compensate for the changes to Sundays:
return Math.round((dateto - datefrom) / (1000 * 60 * 60 * 24)) / 7 * 5 + after - before
}
document.addEventListener("input", function () {
var datefrom = new Date(document.getElementById("datefrom").value);
var dateto = new Date(document.getElementById("dateto").value);
document.getElementById("numdays2").textContent = getDays(datefrom, dateto);
});
From: <input type="date" id="datefrom" value="2021-01-01"><br>
To: <input type="date" id="dateto" value="2021-01-01"><br>
Number of working days: <span id="numdays2">1</span>

Related

JavaScript - check if input date is within add 7 days from current yyyy/mm/dd date, NOT js date()

I have a form submit with 2 date inputs: share_start and share_end in yyyy-mm-dd format. I use JS to validate the input and want to check whether share_end date is within 7 days from the share_start date.
Now, the tricky bit is that I don't have a JS date() dates/timestamps, but only those input dates, but when trying to add on 7 days to the input in JS all I end up with an error since JS needs to operate with date(). I cannot use any external scripts like moment.js to help with this.
Does JS have some sort of in-built function like PHPs strtotime where I can just add + 7 days or something?
Thank you
// Form Submit Validation
function validateForm() {
var share_start = '2021-05-07';
var share_end = '2021-05-15';
var share_max = share_start.setDate(date.getDate() + 6);
if (share_end > share_max) {
alert("Share End Date cannot be more than 7 days from now");
return false;
}
}
At last figured it out.... Bloody JS date conversion is really a pain without libraries such moments.js
var date1 = '2021-01-01';
var date2 = '2021-01-08';
var diffTime = Math.abs(date2 - date1);
var diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
if (diffDays > 6) {
alert("Share cannot be longer than 6 days");
return false;
}
In my particular case, I am getting the date values from a variable, which I then calculate the difference in seconds, after which I convert those seconds to days. Followed by a simple if statement where I check if the value is greater than x days, and I am good to go.

Comparing the current date with a date received from an api response [duplicate]

This question already has answers here:
How to calculate date difference in JavaScript? [duplicate]
(24 answers)
Closed 4 years ago.
I want to compare the date I receive from an API to the current date and if it exceeds 14 days. The date I receive is in this format.
"date": "2018-08-07T14:17:24+02:00"
You can use the library date-fns to calculate this too. It has a smaller bundle size than Moment.
function exceedsDays(date, numberOfDays) {
var today = dateFns.startOfToday();
var diff = dateFns.differenceInDays(today, dateFns.parse(date));
return diff > numberOfDays;
}
var date = "2018-08-07T14:17:24+02:00";
var result = exceedsDays(date, 14);
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/date-fns/1.29.0/date_fns.min.js"></script>
let dateFrom = new Date("2018-08-07T14:17:24+02:00").getTime();
let today = new Date().getTime();
let days14 = 1000 * 60 * 60 * 24 * 14;
if(today - dateFrom > days14){ }
If you go with momentjs you can do something like that. This will return you a boolean. You can reuse later this function to maybe check if more than 30 days etc. Just need to change the second argument. The first one is your date you want to check. By default moment() return now, this is the reason we don't need to create a date for now.
const oldDate = '2018-08-07T14:17:24+02:00';
function exceedNumOfDays(date, numOfDays) {
return moment().diff(new Date(date), 'days') > numOfDays;
}
exceedNumOfDays(oldDate, 14)
I put the code on codesandbox, you can see the console at the bottom left. https://codesandbox.io/s/oo967v83xq

In javascript how can I compare two timestamps to see how many days difference they are [duplicate]

This question already has answers here:
How to calculate number of days between two dates?
(42 answers)
Closed 6 years ago.
In javascript how can I compare two timestamps to see how many days difference they are?
Current code I have:
var todaysDate = Math.floor(Date.now() / 1000);
for (var i = 0; i < 1; i++) {
var job = this.listOfJobs[i];
var jobDate = Date.parse(job.timestamp) / 1000;
//now how would I compare these two timestamps to see how many days apart they are e.g. todaysDate and jobDate
}
The 2 timestamps I have for example are:
todays date: 1475336651
And the job created date: 1465337544
I've substracted those and it equals: 9999107
How many days is 9999107?
This one should do the job. I've added Math.abs in case you put a date from the future, as the 'otherDate' to avoid a negative number.
Also remember, that the first month is 0 - January.
function x(){
var now = new Date();
var otherDate = new Date(2015,09,01);
return Math.abs((now - otherDate)/(1000*60*60*24));
}
And the converter: The result divided by 1000ms * 60s * 60min * 24hrs will give you the amount of days that have passed (or will).
Subtract the two variables and store it in a new variable

javascript wrong date / days calculation

I need to calculate the number of nights between 2 dates, it works but it's very odd.
If I pick dates like 22,06,2015 and 22,07,2015 it shows me 31 nights, which is wrong since June has only 30 days.
if I pick dates like 01,07,2015 and 31,07,2015 it shows me 30 nights, which is correct.
if I pick dates like 01,07,2015 and 1,08,2015 it shows me 31 nights etc.
if I pick dates like 30,09,2015 and 30,10,2015 it shows me 31.041666666666668 nights which is odd and incorrect.
Hope you can help me with this one. Here's the code:
var date11 = $("#in").val();
var date22 = $("#out").val();
// First we split the values to arrays date1[0] is the year, [1] the month and [2] the day
date111 = date11.split('-');
date222 = date22.split('-');
// Now we convert the array to a Date object, which has several helpful methods
date1 = new Date(date111[2], date111[1], date111[0]);
date2 = new Date(date222[2], date222[1], date222[0]);
// We use the getTime() method and get the unixtime (in milliseconds, but we want seconds, therefore we divide it through 1000)
date1_unixtime = parseInt(date1.getTime() / 1000);
date2_unixtime = parseInt(date2.getTime() / 1000);
// This is the calculated difference in seconds
var timeDifference = date2_unixtime - date1_unixtime;
// in Hours
var timeDifferenceInHours = timeDifference / 60 / 60;
// and finaly, in days :)
var timeDifferenceInDays = timeDifferenceInHours / 24;
Thanks a million!
You aren't subtracting 1 from the calendar month number:
date1 = new Date(date111[2], date111[1] - 1, date111[0]);
--------^^^^
Months are zero indexed. you should probably also round the result as if you cross a daylight saving boundary, the time value won't be an even number of days, it will be out by 1 hour (unless you cross two boundaries…)

How to convert time e.g. 00:31:26 into a number in javascript [duplicate]

This question already has answers here:
Convert HH:MM:SS string to seconds only in javascript
(14 answers)
Closed 8 years ago.
I need to compare the run times of marathon runners, im having difficulty comparing the run times as they are in the following format; 00:31:26, 00:34:29 (Hours:Minutes:Seconds).
Ideally I would like to convert the whole time into minutes so that I could then use the times to create a graph.
How could I convert the race times into a number using javascript or otherwise?
This example demonstrates Array.split to split the string into components, hours, minutes and seconds which are held in the variable array. It then uses parseInt to convert the component strings into an integer, which are then in turn mathematically multiplied and added together to give you a representation in seconds.
var time = "01:32:29";
var array = time.split(":");
var seconds = (parseInt(array[0], 10) * 60 * 60) + (parseInt(array[1], 10) * 60) + parseInt(array[2], 10)
console.log(seconds);
On jsfiddle
Same basic method, more succinctly
'02:04:03'.split (':').reduce (function (seconds, v) {
return +v + seconds * 60;
}, 0) / 60;
The split creates an array, the reduce and its function calculates the time in seconds, which is finally divided by 60 to get minutes as a floating point number. The result of the above is 124.05.
Without a library, I would use something like this
convertToMinutes = function(timeString) {
var hms = timeString.split(':');
return Math.ceil(parseInt(hms[2])/60) + parseInt(hms[1]) + parseInt(hms[0])*60
}
demo
http://jsbin.com/awiyir/1/edit
It's also possible to use the built in Date object. Then you can use built in functions for calculations, formatting etc.
Since Date is a date and not a simple time, I suggest aligning it with unix time. Then .getTime() will get the correct number of milliseconds.
var time1 = new Date ('01 01 70 00:31:26 UTC');
var time2 = new Date ('01 01 70 00:29:15 UTC');
var timediff=time1-time2; // Gets the time diff in millisecs
It is a bit hackish, but it works well.
More about the Date object: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date
First you need to convert into seconds as you have your time in hh:mm:ss. If you convert direct to minutes, you may not get exact time. You need to implement it this way :
Example :
var hms = '03:09:56'; // your input string
var a = hms.split(':'); // split it at the colons
// minutes are worth 60 seconds. Hours are worth 60 minutes.
var seconds = (+a[0]) * 60 * 60 + (+a[1]) * 60 + (+a[2]);
//if you want hours
var minutes = (seconds)/60;
console.log(minutes);

Categories