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>
);
}
Related
I have a problem with creating a calendar in JavaScript. I want to display dates from Monday to Sunday. So this is my DateSet function:
dateSets(year) {
const today = new Date();
year = today.getFullYear();
let firstDayOfWeek = this.getDateOfWeek(this.currentWeekNumber, year);
let dates = [];
for (let i = 0; i < 7; i++) {
dates.push(
new Date(firstDayOfWeek.setDate(firstDayOfWeek.getDate() + i))
);
}
return dates;
}
getDateOfWeek(this.currentWeekNumber, year) gets the Monday of the week. But with this code displays 9/8/2021 10/8/2021 12/8/2021 15/8/2021 19/8/2021 24/8/2021 30/8/2021.
So when I change the i in the for with 1 it displays like this but I cannot use this because I cannot get Monday: 10/8/2021 11/8/2021 12/8/2021 13/8/2021 14/8/2021 15/8/2021 16/8/2021.
I'm trying to get this Code working for me:
https://codepen.io/bbarry/pen/Eopdk
I want the calender to start at monday. I already changed the days:[] from Sa-So to Mo-Su in the .js.
But this changes only the header. The dates are still wrong, the 1st of december is still on a Wednesday, but it should be a Tuesday this year.
I'm pretty sure the problem is somewhere in the near this part in the .html:
<thead>
<tr class="c-weeks">
{{ for (i = 0; i < 7; i++) { }}
<th class="c-name">
{{: days[i] }}
</th>
{{ } }}
</tr>
</thead>
<tbody>
{{ for (j = 0; j < 6 && (j < 1 || mode === 'month'); j++) { }}
<tr>
{{ for (i = 0; i < 7; i++) { }}
{{ if (thedate > last) { dayclass = nextmonthcss; } else if (thedate >= first) { dayclass = thismonthcss; } }}
<td class="calendar-day {{: dayclass }} {{: thedate.toDateCssClass() }} {{: date.toDateCssClass() === thedate.toDateCssClass() ? 'selected':'' }} {{: daycss[i] }} js-cal-option" data-date="{{: thedate.toISOString() }}">
<div class="date">{{: thedate.getDate() }}</div>
{{ thedate.setDate(thedate.getDate() + 1);}}
</td>
{{ } }}
</tr>
{{ } }}
</tbody>
I already tried to change the loop (i = 0; i < 7; i++) But I am not able to fix it.
The loop for (i = 0; i < 7; i++) in html file just print 7 header cells, iterating the array days and printing the array value in the cell. As you have seen, this not affects the date. You need to handle the date object.
You have 2 date objects in the html file: one used for month view, and the other used for week view and day view.
Month view
Date object is instantiated at line 12 of html file:
first = new Date(year, month, 1),
This means new date object, passing arguments year (above as current year) and month (defined above as current year). Third argument is the day of the month to be considered as first day of the month. Set this parameter 0.
first = new Date(year, month, 0),
Week view
Date object is instantiated at line 20 of html file:
thedate = new Date(date);
and date is set at line 21:
thedate.setDate(date.getDate() - date.getDay());
Just set date as follows:
thedate.setDate(date.getDate() - date.getDay()+1);
Day view: no changes needed, because you use the same object of week view.
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date
I must modify a code in javascript that is used extensively, so I would like to not have to recreate the entire calendar code. I need the week to start on Monday, which works actually, except when the month starts on Sunday (for example March 2020). This following code (using getDay) apparently creates the number of empty cells necessary.
for(let i=1; i<date.getDay(); i++)
{
let cell = document.createElement('span');
cell.classList.add('cell');
cell.classList.add('empty');
this.content.appendChild(cell);
}
I'm hoping there is a way to append this when the first day of the month is Sunday. Thanks.
This is how I corrected it. Reminder: we are creating the appropriate number of empty cells for each month.
var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
var firstDayWeek = firstDay.getDay();
if (firstDayWeek > 0){
for(let i=1; i<date.getDay(); i++)
{
let cell = document.createElement('span');
cell.classList.add('cell');
cell.classList.add('empty');
this.content.appendChild(cell);
}
}
else {
for(let i=0; i<6; i++)
{
let cell = document.createElement('span');
cell.classList.add('cell');
cell.classList.add('empty');
this.content.appendChild(cell);
}
}
i'm trying to create a calendar using only pure javascript.
the code i'm working on is below.
i'm new to programming so if there are some remarks or advice i will welcome them and thank you very much.
Filling the Calendar table
function fillCalendar(selectedYearValue, selectedMonthValue, weeks){
if(document.getElementById("calendarRows")){
var x = document.getElementById("calendarRows");
var firstDayInMonth = new Date(selectedYearValue, selectedMonthValue, 1);
var firstDayNameIndex = firstDayInMonth.getDay();
currentMonth = firstDayInMonth.getMonth();
for(j = 0; j <= weeks; j++){
var newRow = x.insertRow(x.rows.length);
newRow.id = 'row'+j;
for(i = 0; i <= 6; i++){
if(i == firstDayNameIndex && currentMonth == firstDayInMonth.getMonth()){
var y = newRow.insertCell(i);
y.innerHTML = firstDayInMonth.getDate() + '<br>Ajouter un Planning';
y.className = 'bg-month border';
y.id = firstDayInMonth.getDate();
if(firstDayNameIndex == 6){
firstDayNameIndex = 0;
firstDayInMonth.setDate(firstDayInMonth.getDate() + 1);
}
else{
firstDayNameIndex++;
firstDayInMonth.setDate(firstDayInMonth.getDate() + 1);
}
}
else{
var y = newRow.insertCell(i);
y.className = 'bg-not-month';
}
}
}
}
}
getting the number of weeks in the given month
function getWeeks(selectedYearValue, selectedMonthValue){
var weeks = 0; //weeks to return
var firstDayInMonth = new Date(selectedYearValue, selectedMonthValue, 1); //get the first day in the month
var lastdayinmonth = new Date(selectedYearValue, selectedMonthValue + 1, 0); //get the last day in the month
var compar = new Date(selectedYearValue, selectedMonthValue, 1); //comparison date
compar.setDate(compar.getDate() + 1); //comparison date always +1 day
for(i = firstDayInMonth.getDate(); i <= lastdayinmonth.getDate(); i++){
if(firstDayInMonth.getDay() / 6 == 1 && compar.getMonth() == firstDayInMonth.getMonth()){
weeks++;
}
compar.setDate(compar.getDate() + 1);
firstDayInMonth.setDate(firstDayInMonth.getDate() + 1);
}
/*
first we iterate for the entire month
for each time we iterate and get a saturday we add 1 week
there was a problem that was when a saturday is the last day of the month
it adds a weeks even though we don't want it
that's why i added the compar date
when the month in the compar date is different than the month we're iterating for
it don't add another week
*/
return weeks;
}
Filling the Calendar table with the current month
function thisMonth(){
clearCalendar();
var date = new Date();
var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
/////begin : append headers
if(document.getElementById('yearSelect') || document.getElementById('monthSelect')){
if(document.getElementById('yearSelect').length == 0 && document.getElementById('monthSelect').length == 0){
fillSelectYear();
fillSelectMonth();
}
}
if(document.getElementById("yearSelect")){
document.getElementById("yearSelect").value = ""+firstDay.getFullYear()+""; //select the respective year
}
if(document.getElementById("monthSelect")){
document.getElementById("monthSelect").value = ""+firstDay.getMonth()+""; //select the respective month
}
/////end : append headers
/////Begin : Get Number of weeks in month
var weeks = getWeeks(date.getFullYear(), date.getMonth());
/////End : Get Number of weeks in month
/////begin : Creating the calendar
fillCalendar(date.getFullYear(), date.getMonth(), weeks);
/////End : Creating the calendar
}
This is the Html code for the calendar
<table class="table border rounded" id="calendar-table">
<thead class="thead-dark">
<!-- begin : calendar Headers : year and month -->
<tr class="bg-dark">
<td colspan="1" class="text-center">
<button class="btn btn-primary" id="previous"><span>«</span></button>
</td>
<td colspan="5" class="text-center">
<ul class="list-inline">
<li class="list-inline-item">
<select class="custom-select" id="yearSelect">
</select>
</li>
<li class="list-inline-item">
<select class="custom-select" id="monthSelect">
</select>
</li>
<li class="list-inline-item">
<button class="btn btn-primary" id="currentMonthButton">Aujourd'hui</button>
</li>
</ul>
</td>
<td colspan="1" class="text-center">
<button class="btn btn-primary" id="next"><span>»</span></button>
</td>
<tr>
<!-- end : calendar Headers : year and month -->
<!-- begin : calendar Headers : name of days -->
<tr class="text-center">
<th scope="col">Dimanche</th>
<th scope="col">Lundi</th>
<th scope="col">Mardi</th>
<th scope="col">Mercredi</th>
<th scope="col">Jeudi</th>
<th scope="col">Vendredi</th>
<th scope="col">Samedi</th>
<!-- <th scope="col">Lundi</th>
<th scope="col">Mardi</th>
<th scope="col">Mercredi</th>
<th scope="col">Jeudi</th>
<th scope="col">Vendredi</th>
<th scope="col">Samedi</th>
<th scope="col">Dimanche</th> -->
</tr>
<!-- end : calendar Headers : name of days -->
</thead>
<!-- begin : calendar rows : dates -->
<tbody id="calendarRows">
</tbody>
<!-- end : calendar rows : dates -->
</table>
until now my code works perfectly the only problem is that i want to have the calendar days start at monday instead of sunday.
Have a good day.
I found the answer for my question and here it is:
first i changed my function from calculating the number of weeks to get getting the indexes of days in the month.
if the month begins for example in sunday(and sunday index is 0), i just change it's index to 6 so that it can become the last day of the week instead of the first week.
and the other days i simply decreased their index by 1.
Days indexes in the entire month
function getWeekDaysTable(selectedYearValue, selectedMonthValue){
var weekDays = []; //day indexes to return
var firstDayInMonth = new Date(selectedYearValue, selectedMonthValue, 1); //get the first day in the month
var lastdayinmonth = new Date(selectedYearValue, selectedMonthValue + 1, 0); //get the last day in the month
for(i = firstDayInMonth.getDate(); i <= lastdayinmonth.getDate(); i++){
if(firstDayInMonth.getDay() == 0){
weekDays.push(6);
}else{
weekDays.push(firstDayInMonth.getDay()-1);
}
firstDayInMonth.setDate(firstDayInMonth.getDate() + 1);
}
return weekDays;
}
for filling the calendar i just did a loop on the result of the getWeekDaysTable instead of doing a loop on the entire month indexes.
Filling the Calendar
function fillFrCalendar(selectedYearValue, selectedMonthValue, weeks){
if(document.getElementById("calendarRows")){
var x = document.getElementById("calendarRows");
var firstDayInMonth = new Date(selectedYearValue, selectedMonthValue, 1);
var countWeekDays = 0;
var weekDays = getWeekDaysTable(firstDayInMonth.getFullYear(), firstDayInMonth.getMonth());
var firstDayNameIndex = firstDayInMonth.getDay();
var currentMonth = firstDayInMonth.getMonth();
for(j = 0; j <= weeks; j++){
if(currentMonth == firstDayInMonth.getMonth()){
var newRow = x.insertRow(x.rows.length);
newRow.id = 'row'+j;
for(i = 0; i <= 6; i++){
if(i == weekDays[countWeekDays]){
var y = newRow.insertCell(i);
y.innerHTML = firstDayInMonth.getDate() + '<br>Ajouter un Planning';
y.className = 'bg-month border';
y.id = firstDayInMonth.getDate();
if(firstDayNameIndex == 6){
firstDayNameIndex = 0;
firstDayInMonth.setDate(firstDayInMonth.getDate() + 1);
countWeekDays++;
}
else{
firstDayNameIndex++;
firstDayInMonth.setDate(firstDayInMonth.getDate() + 1);
countWeekDays++;
}
}
else{
var y = newRow.insertCell(i);
y.className = 'bg-not-month';
}
}
}
}
}
}
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.