date difference greater than 90 days with JavaScript not working - javascript

The below script is failing for the scenario : start date 09/12/2009 end date 10/15/2009. The date difference is not more than 90 days, but still fails. can any one help?
var startDate = new Date(document.getElementById('ctl00$MainContent$FromYearTxt').value);
var endDate = new Date(document.getElementById('ctl00$MainContent$ToYearTxt').value);
var monthsDiff = endDate.getMonth() - startDate.getMonth();
var durationLimit = 0;
for (i = 1; i <= monthsDiff; i++) {
durationLimit += new Date(startDate.getFullYear(), startDate.getMonth() + i, 0).getDate();
}
var timeDiff = endDate.getTime() - startDate.getTime();
var daysDiff = Math.floor(timeDiff / (1000 * 60 * 60 * 24));
if (daysDiff > durationLimit) {
args.IsValid = false;
} else {
args.IsValid = true;
}

If you are looking for a 3 month validation, then I think a better choice will be
function test() {
var args = {}; //creating for test
var startDate = new Date(document.getElementById('ctl00$MainContent$FromYearTxt').value);
var endDate = new Date(document.getElementById('ctl00$MainContent$ToYearTxt').value);
var maxDate = new Date(startDate);
maxDate.setMonth(maxDate.getMonth() + 3);
args.IsValid = endDate.getTime() <= maxDate.getTime();
document.getElementById('result').innerHTML = JSON.stringify(args)
}
<input id="ctl00$MainContent$FromYearTxt" value="03/13/2009" />
<input id="ctl00$MainContent$ToYearTxt" value="06/13/2009" />
<button onclick="test()">Test</button>
<div id="result"></div>

Related

Calculate weekdays and weekends count between two dates without considering daylight saving - javascript

Due to daylight saving time in London, I'm not able to get the correct count for weekdays and weekend days. In the below fiddle 26/10/2019 is considering at times as weekday and at times as a weekend.
I want to get the output for the below fiddle is
"workingDays": 1,
"weekendDays": 2
Any suggestions, please?
var startDate = new Date('2019-10-26');
var endDate = new Date('2019-10-28');
var workingDays = number_of_working_days(startDate, endDate);
var weekendDays = number_of_weekend_days(startDate, endDate);
console.log({
'workingDays': workingDays,
'weekendDays': weekendDays
})
function number_of_working_days(startDate, endDate) {
var workingDays = 0;
for (var i = startDate; i <= endDate; i = i + (60 * 60 * 24)) {
if (i.getDay() <= 5) {
workingDays = workingDays + 1;
}
}
return workingDays;
}
function number_of_weekend_days(startDate, endDate) {
var weekendDays = 0;
for (var i = startDate; i <= endDate; i = i + (60 * 60 * 24)) {
if (i.getDay() > 5) {
weekendDays = weekendDays + 1;
}
}
return weekendDays;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

How to calculate the difference between time inputs in javascript?

I want to calculate my work time. It works fine when I input
08:00 - 09:00 = 01:00
But when I input this time
23:30 - 01:30 = 10:00
It should return 02:00
function pad(num) {
return ("0" + num).slice(-2);
}
function diffTime(start, end) {
var s = start.split(":"),
sMin = +s[1] + s[0] * 60,
e = end.split(":"),
eMin = +e[1] + e[0] * 60,
diff = eMin - sMin;
if (diff < 0) {
sMin -= 12 * 60;
diff = eMin - sMin
}
var h = Math.floor(diff / 60),
m = diff % 60;
return "" + pad(h) + ":" + pad(m);
}
document.getElementById('button').onclick = function() {
document.getElementById('delay').value = diffTime(
document.getElementById('timeOfCall').value,
document.getElementById('timeOfResponse').value
);
}
<input type="time" id="timeOfCall">
<input type="time" id="timeOfResponse">
<button type="button" id="button">CLICK</button>
<input type="time" id="delay">
I would use a Date object to calculate the difference in time. Since you are only interested in the time, you can use any date to construct a valid date string. The reason why you are getting 10 hours is because there is no date to show that it is 1am the following day (this is from my understanding of your question).
You can do something like below to get the job done.
const pad = num => (num < 10) ? `0${num}` : `${num}`;
const addADay = (start, end) => {
const sHour = parseInt(start.split(':')[0], 10);
const eHour = parseInt(end.split(':')[0], 10);
return (eHour < sHour);
};
const diffTime = (start, end) => {
const startDate = new Date(`2019/01/01 ${start}:00`);
const endDate = addADay(start, end)
? new Date(`2019/01/02 ${end}:00`)
: new Date(`2019/01/01 ${end}:00`);
const diff = endDate.getTime() - startDate.getTime();
const hours = Math.floor(diff / 3600000);
const min = (diff - (hours * 3600000)) / 60000;
return `${pad(hours)}:${pad(min)}`;
}
console.log(diffTime('08:00','09:00')); // returns 01:00
console.log(diffTime('23:00','01:30')); // returns 02:30
The most important part in the required algorithm is finding if the end date is tomorrow.
based on your code here is a working example with my suggestion.
<!DOCTYPE html>
<html>
<head>
<style>
</style>
</head>
<body>
<input type="time" id="timeOfCall">
<input type="time" id="timeOfResponse">
<button type="button" id="button" onclick="diffTime()">CLICK
</button>
<input type="time" id="delay">
<script>
function pad(num) {
return ("0" + num).slice(-2);
}
function diffTime() {
var start = document.getElementById("timeOfCall").value;
var end = document.getElementById("timeOfResponse").value;
// start date will be today
var d1 = new Date();
var s = start.split(":")
var date1 = new Date(d1.getFullYear(),d1.getMonth(),d1.getDate(),s[0],s[1],0,0);
var s2 = end.split(":")
// end date
if(s2[0] < s[0])
{
// its tommorow...
var ms = new Date().getTime() + 86400000;
var tomorrow = new Date(ms);
d1=tomorrow;
}
var date2 = new Date(d1.getFullYear(),d1.getMonth(),d1.getDate(),s2[0],s2[1],0,0);
var diff = date2.getTime() - date1.getTime();
var msec = diff;
var hh = Math.floor(msec / 1000 / 60 / 60);
msec -= hh * 1000 * 60 * 60;
var mm = Math.floor(msec / 1000 / 60);
msec -= mm * 1000 * 60;
var ss = Math.floor(msec / 1000);
msec -= ss * 1000;
alert(hh + ":" + mm + ":" + ss);
}
document.getElementById("timeOfCall").defaultValue = "23:30";
document.getElementById("timeOfResponse").defaultValue = "01:30";
</script>
</body>
</html>
Hello I have change your code slightly. The explanation is, let your start time is 10:00 and end time is 09:00. Now think with clock wise. the time had to go to 9:00 with 24 hours. So the calculation is difference between 24 and 10 hours and add the rest of the time.
D = E + (24 - S)
function pad(num) {
return ("0" + num).slice(-2);
}
function diffTime(start, end) {
var s = start.split(":"),
sMin = +s[1] + s[0] * 60,
e = end.split(":"),
eMin = +e[1] + e[0] * 60,
diff = eMin - sMin;
if (diff < 0) {
diff = eMin + (24 * 60 - sMin); /* You had to caculate with 24 hours */
}
var h = Math.floor(diff / 60),
m = diff % 60;
return "" + pad(h) + ":" + pad(m);
}
document.getElementById('button').onclick = function() {
document.getElementById('delay').value = diffTime(
document.getElementById('timeOfCall').value,
document.getElementById('timeOfResponse').value
);
}
<input type="time" id="timeOfCall">
<input type="time" id="timeOfResponse">
<button type="button" id="button">CLICK</button>
<input type="time" id="delay">
Here is another simpler way to look at the problem which satisfies all of your test cases, try your all test cases if any case fails then tell me i will fix it.
you just take the hours first and then check if is am or pm and then simply count the minutes.
function diffTime(start, end) {
var s = start.split(":");
var e = end.split(":");
var dHour;
var dMinute ;
var startHour = parseInt(s[0]);
var endHour = parseInt(e[0]);
var startMinute = parseInt(s[1]);
var endMinute = parseInt(e[1]);
// For counting difference of hours
if((startHour>12 && endHour>12) || (startHour<12 && endHour<12))
{
if(startHour<endHour)
{
dHour = endHour - startHour;
}
else if(startHour>endHour)
{
dHour = 24 - ( startHour - endHour);
}
else
{
dHour = 24;
}
}
else if(startHour>12 && endHour<=12)
{
dHour = (24 - startHour) + endHour;
}
else if(startHour<=12 && endHour > 12)
{
dHour = endHour - startHour;
}
else
{
dHour = 24
}
// For Counting Difference of Minute
if (startMinute>endMinute)
{
dMinute = 60 - (startMinute - endMinute);
dHour = dHour - 1;
}
else if(startMinute<endMinute)
{
dMinute = endMinute - startMinute;
}
else
{
dMinute = 0
}
return dHour + " Hours " + dMinute + " Minutes";
}
document.getElementById('button').onclick = function() {
document.getElementById('delay').value = diffTime(
document.getElementById('timeOfCall').value,
document.getElementById('timeOfResponse').value);
}
<input type="time" id="timeOfCall">
<input type="time" id="timeOfResponse">
<button type="button" id="button">CLICK</button>
<input type="text" id="delay">
thank you friend i solve my problem, Miraz Chowdhury's code has done my job
function diff(t1, t2) {
const day = 86400000;
function pad(num) {
return ("0" + num).slice(-2);
}
let time1 = t1.split(":").map(el => parseInt(el));
let time2 = t2.split(":").map(el => parseInt(el));
let zero = (new Date(1990, 0, 1, 0, 0)).setMilliseconds(0)
let aaa = (new Date(1990, 0, 1, time1[0], time1[1])).setMilliseconds(0)
let bbb = (new Date(1990, 0, 1, time2[0], time2[1])).setMilliseconds(0)
let diff = day -Math.abs(aaa - bbb)<Math.abs(aaa - bbb)?day -Math.abs(aaa - bbb):Math.abs(aaa - bbb)
return `${pad(Math.round(diff/1000/60/60))}:${pad(Math.abs(Math.round(diff/1000/60%60)))}`;
}
console.log(diff("09:00", "08:00"));
console.log(diff("23:30", "01:30"));
console.log(diff("01:30", "23:30"));

I'm having issue on send time span from from end to web api

Here I'm finding time difference between two dates and number of hours get calculated like this.
var startdate = $filter('date')(addTeamtask.startdate, 'yyyy-MM-dd hh:mm:ss');
var enddate = $filter('date')(addTeamtask.duedate, 'yyyy-MM-dd 23:59:59');
var sYear = startdate.slice(0, 4);
var eYear = enddate.slice(0, 4);
if (sYear > eYear) { var year = sYear - eYear; var yearhour = year * 8640; } else { year = eYear - sYear; yearhour = year * 8640; }
var sMonth = startdate.slice(5, 7);
var eMonth = enddate.slice(5, 7);
if (sMonth > eMonth) { var month = sMonth - eMonth; var monthhour = month * 720; } else { month = eMonth - sMonth; monthhour = month * 720; }
var Sday = startdate.slice(8, 10);
var Eday = enddate.slice(8, 10);
if (Sday > Eday) { var day = Sday - Eday; var hours = day * 24; } else { day = Eday - Sday; hours = day * 24 }
var totalhours1 = yearhour + monthhour + hours;
var totalhours = totalhours1 +'59:59.544';
But while i send this hours on string format to my web API, it shows {00:00:00} i.e actually time is not binding, Where as if i manually insert hours like this.
var totalhours = "15:58:50.373"
On my API show time as what i had send {15:58:50.373}. So Somebody help me how i may send time dynamically.
I had fix my issue on my own way. like this
var startdate = $filter('date')(addTeamtask.startdate, 'yyyy-MM-dd hh:mm:ss');
var enddate = $filter('date')(addTeamtask.duedate, 'yyyy-MM-dd 23:59:59');
var sYear = startdate.slice(0, 4);
var eYear = enddate.slice(0, 4);
if (sYear > eYear) { var year = sYear - eYear; var yearhour = year * 8640; } else { year = eYear - sYear; yearhour = year * 8640; }
var sMonth = startdate.slice(5, 7);
var eMonth = enddate.slice(5, 7);
if (sMonth > eMonth) { var month = sMonth - eMonth; var monthhour = month * 720; } else { month = eMonth - sMonth; monthhour = month * 720; }
var Sday = startdate.slice(8, 10);
var Eday = enddate.slice(8, 10);
if (Sday > Eday) { var day = Sday - Eday; var hours = day * 24; } else { day = Eday - Sday; hours = day * 24 }
var totalhours1 = yearhour + monthhour + hours;
var totalhours = totalhours1 +'59:59.544';
var totalHoursCaluclutation=totalhours.tostring();
Now API accept my request... Thanks for your commands. Kindly keep support me.

javascript Date count validation - Last 3 months

I populate 2 dates 03-Mar-2015 and 03-Jun-2015, if Last 3 months option is selected.I perform the below JavaScript validation to check for 90 days. But it shows validation error that the two dates selected are greater than 90 days. But my constraint is not allow users to select more than 3 months duration.
function DtTimeDiff(sender, args) {
var startDate = Date.parse(document.getElementById('ctl00$MainContent$FromYearTxt').value);
var endDate = Date.parse(document.getElementById('ctl00$MainContent$ToYearTxt').value);
var timeDiff = endDate - startDate;
daysDiff = Math.floor(timeDiff / (1000 * 60 * 60 * 24));
if (daysDiff > 90) {
args.IsValid = false;
}
else {
args.IsValid = true;
}
}
How to perform validation for 3 months having 91 days(Mar,Apr,May) and 92 days (Jul,Aug,Sep)? Constrain is not allow users to select more than 3 months duration.
You can add the intermediate code to compute the month duration based on the dates:
function DtTimeDiff() {
var startDate = new Date(document.getElementById('ctl00$MainContent$FromYearTxt').value);
var endDate = new Date(document.getElementById('ctl00$MainContent$ToYearTxt').value);
var monthsDiff = endDate.getMonth() - startDate.getMonth();
var durationLimit = 0;
for (i = 1; i <= monthsDiff; i++) {
durationLimit += new Date(startDate.getFullYear(), startDate.getMonth() + i, 0).getDate();
}
var timeDiff = endDate.getTime() - startDate.getTime();
var daysDiff = Math.floor(timeDiff / (1000 * 60 * 60 * 24));
if (daysDiff > durationLimit) {
args.IsValid = false;
} else {
args.IsValid = true;
}
}
You can try calculate month and date separately
function DtTimeDiff(sender, args) {
startDate = new Date("03-03-2015");/*Assume format is MM-DD-YYYY*/
endDate = new Date("06-01-2015");/*Assume format is MM-DD-YYYY*/
var timeDiff = endDate - startDate;
startDateMonth = startDate.getMonth() + 1;
endDateMonth = endDate.getMonth() + 1;
startDateDate = startDate.getDate();
endDateDdate = endDate.getDate();
if (endDateMonth - startDateMonth >= 3) {
if (endDateDdate - startDateDate >= 0) {
args.IsValid = true;
console.log("In");
} else {
args.IsValid = false;
console.log("Out");
}
}
}

Calculate days left to a specific date with JavaScript

I was trying to calculate the days left until a specific date. I know that there are a million different approaches and tutorials about it, but I wanted to write a code by myself. The problem is that the output of the function is "NaN". I am very thankful for your help.
This is my code:
var daysLeft = function(input) {
var num = '';
var date = [];
var x = 0;
for (i = 0; i < input.length; i++) {
if (!isNaN(input.charAt(i))) {
num += input.charAt(i);
}
else {
date[x] = parseInt(num, 10);
x++;
}
}
var inputDate = new Date(date[2], date[1], date[0]);
var today = new Date();
var timeDiff = Math.abs(inputDate.getTime() - today.getTime());
return Math.ceil(timeDiff / (1000*3600*24));
};
daysLeft("11.12.2014");
BTW: I wrote this code, because the Date() function works with the American format of Dates (MM/dd/YYYY) and not with UTC dates. I am also aware that there is the Date.UTC() function, but anyway. I just wanted to turn around months and days myself.
When you parse num to set date[x], you need to reset num to ''.
...
else {
date[x] = parseInt(num, 10);
x++;
num = '';
}
You might consider using String.split() to separate your input at the periods.
My Solution is:
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
var daysLeft = function(input) {
var num = '';
var date = [];
var x = 0;
for (i = 0; i < input.length; i++) {
if (!isNaN(input.charAt(i)) && isNumeric(input.charAt(i))) {
num += input.charAt(i);
}
else {
date[x] = parseInt(num, 10);
x++;
num = '';
}
}
date[x] = parseInt(num, 10);
var inputDate = new Date(date[2], date[1], date[0]);
var today = new Date();
var timeDiff = Math.abs(inputDate.getTime() - today.getTime());
return Math.ceil(timeDiff / (1000*3600*24));
};
But a better would be:
function parseDate(input) {
var parts = input.split('-');
// new Date(year, month [, day [, hours[, minutes[, seconds[, ms]]]]])
return new Date(parts[0], parts[1]-1, parts[2]); // Note: months are 0-based
}
var daysLeft = function(input) {
var inputDate = parseDate(input);
var today = new Date();
var timeDiff = Math.abs(inputDate.getTime() - today.getTime());
return Math.ceil(timeDiff / (1000*3600*24));
};
You should use something like this:
var daysLeft = function(input) {
var num = '';
var date = [];
var x = 0;
for (i = 0; i < input.length; i++) {
if (!isNaN(input.charAt(i))) {
num += input.charAt(i);
}
else {
date[x] = parseInt(num, 10);
x++;
num='';
}
}
date[x] = parseInt(num, 10);
var inputDate = new Date(date[2], date[1], date[0]);
var today = new Date();
var timeDiff = Math.abs(inputDate.getTime() - today.getTime());
return Math.ceil(timeDiff / (1000*3600*24));
};
daysLeft("11.12.2014");

Categories

Resources