I'm creating a calendar with JavaScript and need to be able to scroll to the next month and get the day the month starts on and be able to show all of the days in the month. I can do this for January but am confused how to make it work for each month when scrolling forward or backwards. Also I am able to scroll to the next month's name but am confused on how to get the days for the next month.
var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August',
'Septemeber', 'October', 'November', 'December']
var getMonths = document.querySelector('.twelvemonths');
var showMonth = document.querySelector('.show-month')
var showWeekDays = document.querySelector('.weekday');
var dateContainer = document.querySelector('.date-container');
var scrollRight = document.querySelector('.go-right');
var scrollLeft = document.querySelector('.go-left');
let weekDay = new Date();
let d = new Date();
let day = d.getDay();
let month = d.getMonth();
let year = d.getFullYear();
function getDaysInMonth(year, month){
return new Date(year, month, 0).getDate()
}
const getDays = getDaysInMonth(year, month)
function drawDays(){
for(i = 1; i <= getDays; i ++){
let calendarDay = document.createElement('div')
calendarDay.className = 'calendar-day';
calendarDay.innerHTML = i;
dateContainer.appendChild(calendarDay);
}
}
scrollRight.addEventListener('click', () =>{
if(month < 11){
month ++;
} else {
month = 0;
}
showMonth.innerHTML = months[month];
})
scrollLeft.addEventListener('click', () =>{
month--;
if(month < 0){
month = 11;
}
showMonth.innerHTML = months[month]
})
showMonth.innerHTML = months[month];
drawDays()
switch(day){
case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;
case 2:
day = "Tuesday";
break;
case 3:
day = "Wednesday";
break;
case 4:
day = "Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day = "Saturday";
break;
}
Related
How would I add an ID to each day with the following code? I thought I could just use days.id but this doesn't seem to work. I want each calendar day to have an ID so I can get events from local storage.
for (i = 1; i<= lastDay; i++ ){
days += `<div>${i}</div>`;
}
I have tried days.id Math.random(1,100) but this is not working.
Here is the full javascript code
const date = new Date();
const renderCalendar = () =>{
const monthDays = document.querySelector('.days');
const calendar = document.querySelector('.calendar')
let lastDay = new Date(date.getFullYear(), date.getMonth() +1, 0).getDate();
let prevLastDay = new Date(date.getFullYear(), date.getMonth(), 0).getDate();
const firstDayIndex = new Date(date.getFullYear(), date.getMonth(), 1).getDay();
const lastDayIndex = new Date(date.getFullYear(), date.getMonth() + 1, 0).getDay();
const months = [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December'
]
document.querySelector('.date h1').innerHTML = months[date.getMonth()];
document.querySelector('.date p').innerHTML = date.toDateString();
let days = '';
for (x = firstDayIndex; x > 0; x--){
days += `<div class="prev-date">${prevLastDay - x +1}</div>`
}
for (i = 1; i<= lastDay; i++ ){
days += `<div>${i}</div>`;
}
for (j = 1; j< 7 - lastDayIndex; j++){
days += `<div>${j}</div>`;
}
monthDays.innerHTML = days
}
document.querySelector('.calendar').addEventListener('click', (e) =>{
console.log(e.target.innerHTML)
})
document.querySelector('.prev').addEventListener('click', () =>{
date.setMonth(date.getMonth() -1)
renderCalendar();
})
document.querySelector('.next').addEventListener('click', () =>{
date.setMonth(date.getMonth() +1)
renderCalendar();
})
renderCalendar();
I've written script for both current month & following month (shown below). However, I am trying to achieve something in the middle; displaying the current month until the 15th day, then changing to next month after the 15th day.
Example:
If today is July 10th, display “July”.
If today is July 20th, display “August”.
Displaying the Current Month, alternating: “var n = month[d.getMonth()];”
{
var month = new Array();
month[0] = "January";
month[1] = "February";
month[2] = "March";
month[3] = "April";
month[4] = "May";
month[5] = "June";
month[6] = "July";
month[7] = "August";
month[8] = "September";
month[9] = "October";
month[10] = "November";
month[11] = "December";
var d = new Date();
var n = month[d.getMonth()];
document.write (month = n)
}
Displaying the Following Month, alternating: “var n = month[d.getMonth()+1];”
{
var month = new Array();
month[0] = "January";
month[1] = "February";
month[2] = "March";
month[3] = "April";
month[4] = "May";
month[5] = "June";
month[6] = "July";
month[7] = "August";
month[8] = "September";
month[9] = "October";
month[10] = "November";
month[11] = "December";
var d = new Date();
var n = month[d.getMonth()+1];
document.write (month = n)
}
I've experimented with values in between the 0-1, but still no luck. I haven't managed to find a solution after a lot of research so any help would be much appreciated.
Thanks in advance,
Ryan.
You can get the day of the month with new Date().getDate(). Then, if it is more than 15, add 1 to the month index to return.
Also, I rewrote your months array in a simple form instead of month[0] = "January";
{
var month = ["January","February","March","April","May","June","July","August","September","October","November","December"]
var d = new Date();
var dayOfMonth = d.getDate();
var n = month[ d.getMonth() + (dayOfMonth > 15 ? 1 : 0) ];
document.write ("month = " + n)
}
We can create a function to return the month name from the month, and a function to get the next month.
Then, if the current day is 15 or greater, we'll show the next month:
function getMonthName(month, locales = 'default') {
return new Date(new Date().getFullYear(), month, 1).toLocaleString(locales, { month: 'long'} );
}
function getNextMonth(month) {
return (month + 1) % 12;
}
function getMonthToDisplay(date) {
let month = date.getMonth();
if (date.getDate() >= 15) {
month = getNextMonth(month);
}
return getMonthName(month);
}
let dates = ["2021-06-14T18:00:00Z","2021-06-15T00:00:00Z", "2021-09-30T00:00:00Z", "1965-11-01T15:00:00Z"].map(dt => new Date(dt));
for(let d of dates) {
console.log("Date:", d.toDateString(), "Current:", getMonthName(d.getMonth()), "Display:", getMonthToDisplay(d))
}
console.log("Testing all days in June 2021...");
dates = [...Array(30).keys()].map((v,k) => new Date(2021, 5, k + 1));
for(let d of dates) {
console.log("Date:", d.toDateString(), "Current:", getMonthName(d.getMonth()), "Display:", getMonthToDisplay(d))
}
You can get
date -> new Date().getDate()
month -> new Date().getMonth()
and compare date with 15 and get the desired result.
var month = new Array();
month[0] = "January";
month[1] = "February";
month[2] = "March";
month[3] = "April";
month[4] = "May";
month[5] = "June";
month[6] = "July";
month[7] = "August";
month[8] = "September";
month[9] = "October";
month[10] = "November";
month[11] = "December";
const now = new Date();
const mon = now.getMonth();
const date = now.getDate();
const result = date > 15 ? month[mon + 1] : month[mon];
console.log(result);
document.write(result)
I need help in getting the last 3 months in javascript. I have generated an excel sheet in which the user has to populate month number in month column and year in year column.
I need to validate that the user has entered correct month and year combination based on current year.
User fill up the excel and upload it to node js fastify server. After that, I need to validate the month and year.
example:
If the current year is 2018 and the month is Jan(1). Users can enter 2017 in a year and 10 in a month.
The current year is 2019 and the month is 10. User can enter 8 in month
Please guide me. How can I achieve this?
const months = ['January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December'];
const getLastThreeMonths = () => {
const now = new Date();
const previousMonths = [];
for (let i = 0; i < 3; i += 1) {
previousMonths.push(`${months[(now.getMonth() - i)]}`);
}
return previousMonths;
};
console.log(getLastThreeMonths());
one working code sample is here ..You can change the content as per your requirement.
$(document).ready(function () {
var date = new Date();
var month = date.getMonth() + 1;
var year = date.getFullYear();
if (month == "1") {
year = date.getFullYear() - 1;
}
month = month - 2;
$("#month").on('change', function () {
if ($("#month").val() != month) { alert("not valid month"); }
});
$("#year").on('change', function () {
if ($("#year").val() != year) {alert("not valid year"); }
});
});
<input type="text" id="month" placeholder="put month here"/>
<input type="text" id="year" placeholder="put year here"/>
My Answer:
const dateValidator = (month, year) => {
const allowedRange = [];
for (let i = 1; i <= 3; i += 1) {
const current = new Date();
current.setMonth(current.getMonth() - i + 1);
allowedRange.push({ month: current.getMonth() + 1, year: current.getFullYear() });
}
return allowedRange.find(ar => ar.month === month && ar.year === year);
};
I have a perfectly functioning clock.js widget that I'm using to display date and time on multiple displays throughout our offices in several states.
The offices in the Eastern timezone have no issue, as this defaults to eastern time (our server running the screens for every display is eastern).
However, I want to add a conditional in here (say if $screenID == 3 {... so that on the screens in the Central time zone it shows the proper central time.
How should I go about adding a block in here for that condition to show central rather than eastern?
function startTime() {
var today = new Date();
var hr = today.getHours();
var min = today.getMinutes();
// var sec = today.getSeconds();
ap = (hr < 12) ? "<span>AM</span>" : "<span>PM</span>";
hr = (hr == 0) ? 12 : hr;
hr = (hr > 12) ? hr - 12 : hr;
//Add a zero in front of numbers<10
hr = checkTime(hr);
min = checkTime(min);
// sec = checkTime(sec);
document.getElementById("clock").innerHTML = hr + ":" + min + " " + ap;
var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
var curWeekDay = days[today.getDay()];
var curDay = today.getDate();
var curMonth = months[today.getMonth()];
// var curYear = today.getFullYear();
var date = curWeekDay+", "+curDay+" "+curMonth;
document.getElementById("date").innerHTML = date;
var time = setTimeout(function(){ startTime() }, 500);
}
function checkTime(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
Use timezones.
function startTime(screen, loc) {
var timeZone = "America/Chicago";
if (screen === 1)
timeZone = "America/New_York";
var dateOptions = { weekday: 'long', day: 'numeric', month: 'long', timeZone: timeZone };
var timeOptions = { hour: 'numeric', minute: 'numeric', timeZone: timeZone };
var dt = new Date();
document.getElementById("myclock" + loc).innerHTML = dt.toLocaleString("en-US", timeOptions);
document.getElementById("mydate" + loc).innerHTML = dt.toLocaleString("en-NZ", dateOptions);
}
startTime(0, 1);
startTime(1, 2);
<div id="myclock1">asdf</div>
<div id="mydate1">asdf</div>
<hr>
<div id="myclock2">asdf</div>
<div id="mydate2">asdf</div>
I'm trying to find the actual position of a weekday in constant time. I get it working with loop but trying to find out it with some Mathematics. I know it is like divide it by 7 but not getting it work.
Here is the code.
for(var ind=0; ind<=between.length; ind++){
if (new Date(between[ind]).getMonthWeek() === baseDtWk && new Date(between[ind]).getDay() === baseDtD) {
datesToBeMarked.push(between[ind]);
console.log(" :Date: " + between[ind] + " :Week: " + new Date(between[ind]).getMonthWeek());
console.log("Date entered : " + new Date(between[ind]));
}
}
I have done this few days back. It is as simple as the code below. :)
On fiddle.
Number.prototype.nth= function(){
var n= Math.round(this), t= Math.abs(n%100), i= t%10;
if(i<4 && (t<4 || t> 20)){
switch(i){
case 1:return n+'st';
case 2:return n+'nd';
case 3:return n+'rd';
}
}
return n+'th';
}
Date.prototype.nthofMonth= function(){
var today= this.getDate(),m=this.getMonth(),
day= ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday',
'Friday', 'Saturday'][this.getDay()],
month= ['January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December'][m];
return [(m+1)+'-'+today,'the ', Math.ceil(today/7).nth(), day, 'of', month, 'in', this.getFullYear()].join(' ');
}
var date=new Date().nthofMonth();
console.log(date);
You haven't shown how you want the result to look, I guess you want to know if a particular date is, say, the nth Tuesday, e.g.
// Add ordinal to a number
function addOrdinal(n) {
var ord = [,'st','nd','rd'];
var a = n % 100;
return n + (ord[a>20? a%10 : a] || 'th');
}
// Return the ordinal number of a day in the month
function ordinalDay(d) {
d = d || new Date();
var days = ['Sunday','Monday','Tuesday','Wednesday',
'Thursday', 'Friday','Saturday'];
return addOrdinal(Math.ceil(d.getDate()/7)) + ' ' + days[d.getDay()];
}
console.log(ordinalDay(new Date(2015,0,1))); // 1st Thursday
console.log(ordinalDay(new Date(2015,0,27))); // 4th Tuesday
console.log(ordinalDay(new Date(2015,0,31))); // 5th Saturday
console.log(ordinalDay(new Date(2015,11,25))); // 4th Friday