Reputation: 21
i want to write a calendar in javascript. For the calendar i generated a table with javascript and in one row i want to display the day of the week for each date. But the table shows only undefined. I dont know whats wrong.
Here is the function, which should calculate the day:
var currentDay = function (currentMonth) {
var month_code = ["6", "2", "2", "5", "0", "3", "5", "1", "4", "6", "2", "4"];
var year_digit = currentYear - 2000;
var year_code = (year_digit + (year_digit / 4)) % 7;
currentDay = ((1 + month_code[currentMonth] + year_code) % 7) - 1;
return currentDay; }
I calculate the day with the formula:
("day in the month" + Month-code + Year-Code) % 7
the Month-Code is fixed and in the "month_code"-Array. It beginns with January and ends with December. The Year-Code i can calculate with the last two digits from the current Year. Then we divide these by 4. After that we add the last two digits. And then we have to calculate the sum modulo 7 and we have the Year-Code.
For example: (I use the date, which I wrote the question: 04.04.2020) day of the month: 4 month-code: 5 year-code: 2020 --> 20 ; 20/4 = 5; 5 +20 = 25; 25%7 = 4 --> year-code is 4
(4+5+4) % 7 = 6
now i have to subract 1 from the result, because the array with starts with 0 and not 1.
var day_of_week = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
day_of_week[5]="Sat";
And Today is Saturday.
I hope someone can help me
Upvotes: 1
Views: 527
Reputation: 6872
Is there a reason you're not using Date
objects?
With a date object you can get the week day by calling toLocaleString
with the option weekday
set to either short
or long
.
const dateString = '05/23/2014';
const date = new Date(dateString);
console.log(`${dateString} was a ${date.toLocaleString('en-us', {weekday:'long'})}`);
const today = new Date();
console.log(`Today is a ${today.toLocaleString('en-us', {weekday:'short'})}`);
Upvotes: 2