How to match a date between given date difference in JavaScript - javascript

I have a script that calculates the number of weeks between two given dates.
and then creates a table where number of row equals number of weeks .
script looks like this
JSFIDDLE
Script
$('#test').click(function () {
// Here are the two dates to compare
var date1 = '29-10-2015';
var date2 = '29-12-2015';
var Targetvalue = parseFloat("1000000");
var dealjson = '[{"dealdate":"25-11-2015","cost":200000}]';
// First we split the values to arrays date1[0] is the year, [1] the month and [2] the day
date1 = date1.split('-');
date2 = date2.split('-');
// Now we convert the array to a Date object, which has several helpful methods
date1 = new Date(date1[2], date1[1], date1[0]);
date2 = new Date(date2[2], date2[1], date2[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;
var timeDifferenceInWeeks = Math.round(timeDifferenceInDays / 7);
// alert(timeDifferenceInDays/7);
TargetPerweek = Targetvalue / timeDifferenceInWeeks;
//Math.round(timeDifferenceInWeeks);
TargetPerweek = Math.round(TargetPerweek * 100) / 100;
var string = "<table data-role='table' class='ui-responsive'><thead><tr><th>Week</th><th>Target</th><th>Achieved</th></tr></thead>";
for (var i = 1; i <= timeDifferenceInWeeks; i++)
string = string + "<tr><th>Week" + i + "</th><td>" + TargetPerweek + "</td><td></td></tr>";
string = string + "</table>";
$('.varianceData').html(string);
});
HTML
<button id="test">See the Tab</button>
<div class="varianceData"></div>
If you click the button in the fiddle you will see a table with Target and achieved value week wise .
So I want to show the achieved on the respective week he did the deal
Based on the variable dealjson so in the achived column I should show the amount that was achieved in the respective week ;
Expected Out put based on the dealjson
<table data-role="table" class="ui-responsive">
<thead>
<tr>
<th>Week</th>
<th>Target</th>
<th>Achieved</th>
</tr>
</thead>
<tbody>
<tr>
<th>Week1</th>
<td>111111.11</td>
<td>No Deal</td>
</tr>
<tr>
<th>Week2</th>
<td>111111.11</td>
<td>No Deal</td>
</tr>
<tr>
<th>Week3</th>
<td>111111.11</td>
<td></td>
</tr>
<tr>
<th>Week4</th>
<td>111111.11</td>
<td>No Deal</td>
</tr>
<tr>
<th>Week5</th>
<td>111111.11</td>
<td>200000</td>
</tr>
<tr>
<th>Week6</th>
<td>111111.11</td>
<td></td>
</tr>
<tr>
<th>Week7</th>
<td>111111.11</td>
<td>No Deal</td>
</tr>
<tr>
<th>Week8</th>
<td>111111.11</td>
<td>No Deal</td>
</tr>
<tr>
<th>Week9</th>
<td>111111.11</td>
<td>No Deal</td>
</tr>
</tbody>
</table>

You can use setDate() to increase the number of date1 7 days, until it becomes equal to or greater than date2. And compare the deal dates using simple >= && <=, to check if the dates is within the week, you will need a temporary variable.
Here is the updated fiddle. Its not optimized, but it works.

Related

Calendar React JS

I have a homework to make a calendar component on React
It has to show days like Windows calendar, start from Sunday even if it's an other month and ends with Saturday
And HTML has to be made like table (tr (weeks)...td (days)...)
it has to be:
one week:
<tr>
<td>day1</td>
<td>day2</td>
<td>day3</td>
<td>day4</td>
<td>day5</td>
<td>day6</td>
<td>day7</td>
</tr>
then next week the same
I have prepared an array with dates, array starts from Sunday and ends with Saturday
I was trying map() it and put jsx tags with dates inside. That works
But when I'm trying to put inside week tags (tr) I can't do it because I'm trying to put inside
</tr><tr>
closing one week and opening next week (I can't add one closing jsx tag)
I'm stuck
Could you give me some advises?
I give you an example for your reference:
import React from 'react';
export default function Calendar() {
let dateNum = 1;
let firstDay = new Date('2023-02-10'),
firstWeekDay;
let i;
let lastDate;
let month = [];
let week = [];
firstDay.setDate(1);
lastDate = new Date(firstDay.getTime());
lastDate.setMonth(lastDate.getMonth() + 1); // the first day of the next month
lastDate = new Date(lastDate.getTime() - 86400000); //the first day of the next month minus 1 day
firstWeekDay = firstDay.getDay();
for (i = 0; i < firstWeekDay; i++) {
week.push('');
}
for (i = firstWeekDay; i < 7; i++) {
week.push(dateNum++);
}
month.push(week);
console.log(dateNum <= lastDate.getDate());
while (dateNum <= lastDate.getDate()){
week=[];
for (i=0; i <7 ;i++){
if (dateNum <= lastDate.getDate()) {
week.push(dateNum++);
} else {
week.push("");
}
}
month.push(week);
}
return (
<table>
<thead>
<tr>
<td>Sun</td>
<td>Mon</td>
<td>Tue</td>
<td>Wed</td>
<td>Thu</td>
<td>Fri</td>
<td>Sat</td>
</tr>
</thead>
{month.map((week) => (
<tr>
{week.map((day) => (
<td>{day}</td>
))}
</tr>
))}
</table>
);
}

Count specific days between two dates based on a rolling fortnight

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

How to use a value in an input type=text in an if else statement

I made an interface for users to log their in and out times and to calculate the no. of hours worked. However, I don't fully understand the code I used so was hoping to find an easier option to understand.
I need to convert the in and out times from text to make another code to check if the employee had worked a full day (work hours>8hours) or if its a half day etc.
I used this to calculate the work hours (users enter the time as hh:mm)
function diff(a, b) {
function toTime(a) {
return Date.parse('1970-01-01 ' + a.substr(0, 5)) / 1000 +
(a.includes('PM') && (12 * 60));
}
var d = toTime(b) - toTime(a);
return d >= 0 ? new Date(0, 0, 0, 0, 0, d).toTimeString().substr(0, 5) : '';
}
function myFunction() {
var workhours;
workhours = diff($('#in-time').val(), $('#out-time').val());
$('#value').val(workhours);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<th>Employee Name</th>
<th>In Time</th>
<th>Out Time</th>
<th>Hours Worked</th>
</tr>
<tr>
<td>Test</td>
<td><input type="text" id="in-time"></td>
<td><input type="text" id="out-time" onkeyup="myFunction()"></td>
<td><input type="text" id="value"></td>
</tr>
</table>
Edit : If anyone has an easier way to calculate the work hours based on the two inputs, it would be great if anyone can explain so I can learn it for future projects
If anyone else is trying to do something similar, I just made this code that works.
I will update it in a while with comments explaining how I got it to work.
function myFunction() {
var inTime = document.getElementById("in-time").value; // assume its 08:30
var outTime = document.getElementById("out-time").value;// assume its 17:30
var hours = inTime.split(':',1); // array = [08]
var hours2 = outTime.split(':',1); // array = [17]
var minutesArray = inTime.split(':',2); // array = [08,30]
var minutesArray2 = outTime.split(':', 2); // array = [17,30]
var minutes = minutesArray[1]; // select '30' from the array [08,30]
var minutes2 = minutesArray2[1]; // select '30' from the array [17,30]
var hoursToMinutes = hours * 60;
var hoursToMinutes2 = hours2 * 60;
var time = hoursToMinutes + parseInt(minutes);
var time2 = hoursToMinutes2 + parseInt(minutes2);
var workhours =(time2 - time)/60;
document.getElementById("workhours").innerHTML = workhours;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<th>Employee Name</th>
<th>In Time</th>
<th>Out Time</th>
<th>Hours Worked</th>
</tr>
<tr>
<td>Test</td>
<td><input type="text" id="in-time"></td>
<td><input type="text" id="out-time" onkeyup="myFunction()"></td>
<td><span id="workhours"></span></td>
</tr>
</table>

Javascript Date Object incorrect date

Hello I just need another set of eyes on this. I created this code to set a calendar with the current dates on it, it was working fine but today, sat jan 30, the calendar was still showing it start at sat jan 23.
here is the link to my codepen of it:
http://codepen.io/cavascript/pen/MKXrbj
here is the code:
var date = new Date();
var saturday = date.getDate() - date.getDay() - 1;
var sunday = date.getDate() - date.getDay() ;
var monday = date.getDate() - date.getDay() + 1 ;
var tuesday = date.getDate() - date.getDay() + 2 ;
var wednesday= date.getDate() - date.getDay() + 3 ;
var thursday = date.getDate() - date.getDay() + 4 ;
var friday = date.getDate() - date.getDay() + 5 ;
var saturday = (new Date(date.setDate(saturday))).toDateString();
var sunday = (new Date(date.setDate(sunday))).toDateString();
var monday = (new Date(date.setDate(monday))).toDateString();
var tuesday = (new Date(date.setDate(tuesday))).toDateString();
var wednesday = (new Date(date.setDate(wednesday))).toDateString();
var thursday = (new Date(date.setDate(thursday))).toDateString();
var friday = (new Date(date.setDate(friday))).toDateString();
//add to html row
$('#dateRow').html('<td colspan="4">Date</td><td colspan="4">'+saturday+'</td><td colspan="4">'+sunday+'</td><td colspan ="4">'+monday+'</td><td colspan="4">'+tuesday+'</td><td colspan="4">'+wednesday+'</td><td colspan="4">'+thursday+'</td><td colspan="4">'+friday+'</td><td>Hours</td><td>Delete</td>');
And here is the HTML:
<div class="container-fluid">
<div class="table-responsive">
<table class="table table-bordered">
<tbody>
<tr id="dateRow">
</tr>
<tr>
<td colspan="4">Name</td>
<td colspan="2">Br/lnch</td>
<td colspan="2">Dinner</td>
<td colspan="2">Br/lnch</td>
<td colspan="2">Dinner</td>
<td colspan="2">Br/lnch</td>
<td colspan="2">Dinner</td>
<td colspan="2">Br/lnch</td>
<td colspan="2">Dinner</td>
<td colspan="2">Br/lnch</td>
<td colspan="2">Dinner</td>
<td colspan="2">Br/lnch</td>
<td colspan="2">Dinner</td>
<td colspan="2">Br/lnch</td>
<td colspan="2">Dinner</td>
<td>&nbsp</td>
<td>&nbsp</td>
</tr>
</tbody>
</table>
</div>
Thank you for any input
Your code
date.getDate() - date.getDay() - 1;
will return 23 as we are presently on 30/01/2016 - so it does exactly what you asked it to do :)
Check out Date.js or Moment.js which have a great many helper methods to make Datetime arithmetic much easier.
I guess you don't want the week shown to not always be from Saturday 23rd to Fri 29th.
Possible solution: call getDate() check if result is a Saturday use this as var saturday and from there you can deduce Monday - Friday. However, if getDate() is not a Saturday find previous saturday and use that.
Also, a useful resource for calendars
Have a go - if you can't do it then pop me a message and I'll gladly help out.

datepicker calculations

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.

Categories

Resources