What is the best way to create a calendar that displays every day in a single row?

Is it possible to create a calendar with all days in one row?

I've been searching for a solution to this problem without any luck. It's surprising that I haven't found a clear answer or explanation on how to achieve this.

I'm sure many people have accomplished this task before, but the information seems elusive. Does anyone here know how to do this using JavaScript or TypeScript?

Is there a way to display all calendar days in a single row?

Most calendar tables we come across in libraries like JQuery typically show 7 days in one row. However, I would like to see 30 days in a row instead of 7.

For example:

Click here for an example image.

Answer №1

A straightforward and leisurely approach:

var
   startDate = new Date( 2015, 0, 1 )
   , numOfDays = 30
   , days = []
   ;

function addDay( date ) {
   date.setDate( date.getDate() + 1 );
}

while ( numOfDays-- ) {
    var formattedDate = startDate.getDate() + '/' + (startDate.getMonth() + 1) + '/' + startDate.getFullYear();
    days.push(formattedDate);
    addDay(startDate);
}
console.log(days.join());

The output in the console will be:

1/1/2015,2/1/2015,3/1/2015,4/1/2015,5/1/2015,6/1/2015,7/1/2015,8/1/2015,9/1/2015,10/1/2015,11/1/2015,12/1/2015,13/1/2015,14/1/2015,15/1/2015,16/1/2015,17/1/2015,18/1/2015,19/1/2015,20/1/2015,21/1/2015,22/1/2015,23/1/2015,24/1/2015,25/1/2015,26/1/2015,27/1/2015,28/1/2015,29/1/2015,30/1/2015

I utilized a counter to loop through 30 iterations. You have the flexibility to adjust the condition for generating dates within a specific month. However, I find using Julian days more efficient compared to the above method.

Answer №2

Alright, so the key here is to create an array with a specific structure. Let's explore how we can generate this array.

First off, I'd like to introduce you to a library called Moment.js, which we'll be using as an example. Of course, you have the option of using vanilla JavaScript instead.

var moment = require('moment');
var resultArray = [];

var util = {};

/** 
 * input:
 *   month [Number]
 * output:
 *   totalDays [String]
 */
util.getDaysOfMonth = function(month){
  month = +month;
  var totalDays = '31';

  if( /[469]|(11)/.test(month) ){
    totalDays = '30';
  } else if (month === 2) {
    totalDays = moment().isLeapYear() ? '29' : '28';
  }

  return totalDays;
}

// Get current month of the year
var month = moment().get('month') + 1;

// current year
var year  = moment().get('year');
var days  = util.getDaysOfMonth(month);
for(var i = 1; i <= days; i++) {
  var str = month + '/' + i + '/' + year;
  resultArray.push(str);
}

Now that we have our array, you can proceed to format it as needed.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Attempting to include a select element via transclusion

Looking to develop a custom directive named select that will replace a select element with a customized dropdown interface. For a clear example, check out this jsfiddle where the concept is demonstrated. Let's consider the below select element: < ...

Tips for concealing an input IP Address in React

Looking for suggestions on an IP Address mask input solution. The format might vary between 999.99.999.99 and 99.9.99.9, but react-input-mask does not support varying lengths. Any recommendations? ...

Activate the Keypress event to update the input value in React upon pressing the Enter

I am facing an issue where I need to reset the value of an input using a method triggered by onPressEnter. Here is the input code: <Input type="text" placeholder="new account" onPressEnter={(event) => this.onCreateAccount(event)}> < ...

The markers on Google Maps are currently displaying in the wrong position, despite the latitude and longitude being correct

Utilizing the Google Maps API, I have implemented a system to dynamically add map markers tracking 2 of our company's vehicles. The website is developed in asp.net c# mvc with bootstrap 4.3.1. An ajax request retrieves the latest marker location from ...

determining the user's position within the <s:select> element

I have a dropdown select tag in my code with a list of countries. I want the user's country to be auto-selected when they access the page. This is the JSP code snippet: <s:select name="dropdown" list="countries" listKey="value" listV ...

Issue with subscribing to a shared service in Angular 2

I've encountered some challenges with BehaviorSubject while using a shared service across three components: import { Injectable } from '@angular/core'; import { BehaviorSubject } from 'rxjs/BehaviorSubject'; @Injectable() export ...

Open multiple accordion sections simultaneously

In my current setup, I have a paginated loop of elements that contains an accordion. The accordion is implemented using angular-ui-bootstrap. <div data-ng-repeat="m in results"> <div class="stuff_in_the_middle"> <accordion id="a ...

Ways to identify when a chemical reaction has taken place?

I have developed a Discord bot that interacts with an API related to a game server panel. The bot has tasks to start, restart, stop, and kill the server. I want to enable end users to trigger these tasks by reacting to a specific embed posted by the bot. ...

Placing information within a nested array with multiple levels of nesting

I'll try to keep this concise, Here is the structure of the schema... import mongoose from 'mongoose' const QuestionSchema = mongoose.Schema({ questionTitle: { type: String, required: " title"}, questionBody: { type: Stri ...

Modifying the content within a DIV element

I want to make changes to my DIV. <div id="main"> <div id="one"> <div class="red"> ... </div> <img class="avatar" src="img/avatar1.jpg"/> <span class="name"> John < ...

Tips for ensuring that the horizontal scroll bar remains consistently positioned at the bottom of the screen

There are two div sections on a page, with one positioned on the left and the other on the right. The div on the right contains multiple dynamically generated tags which necessitate a horizontal scroll bar (overflow:auto). This causes the div's height ...

Issue with retrieving data from controller in Spring MVC 3 using jQuery and AJAX via $.get method. The value is not being returned to the

I am currently diving into the world of AJAX, particularly in conjunction with Spring MVC. However, I am encountering some challenges along the way. Before delving into my actual real-time project requirements, I decided to test out the AJAX+Spring MVC+jQ ...

receiving an undefined value from a remote JSON object in Node.js

I have been struggling to extract the specific contents of a JSON api without success. Despite my best efforts, the console always returns undefined. My goal is to retrieve and display only the Question object from the JSON data. After spending several h ...

How to install Typed.js without using Node.js

I'm currently working on a project that requires the JavaScript library typed.js, however, I am using the free webhost 000webhost which does not support Node.js. Since typed.js is typically installed using Yarn, NPM, or Bower - all of which require No ...

Strategies for managing the "ref" property of Material-UI component props within our custom components

I have a unique custom component setup as shown below: // ... import { PaperProps, styled } from '@mui/material'; type ComponentProps = PaperProps & { a: string, b: string }; export const MyPaper = styled(Paper)(/* ... */); const Compo ...

method that provides route-specific variable outputs

I have a situation where multiple routes require the same userdata from the database. Although I have a function to verify if the user is logged in, this function does not return the user variables. Here is an example route: app.get('/template', ...

I am facing an issue with Lotties having a black background in my NextJS project. Is there a way to make them transparent

I am facing an issue with my LottieFiles (JSON) displaying a black background when imported into my NextJS project. Despite trying to set background='transparent' on both the Player and parent div, the problem persists. I made sure to export my ...

Ensure that the line above is shorter in length compared to the following line

Is there a way to ensure that the previous line of text is always shorter than the next one, even if the length of the text is unknown? For example: Lorem ipsum dolor sit amet, consectetur adipiscing et libero posuere pellentesque. Vivamus quis nulla jus ...

Tips for returning JSON data using AJAX

When working with native JS, I am familiar with using AJAX to display the output from PHP/mySql that is not Json Encoded in the element "some_id" like this: <script> function addItem(value) { xmlhttp = new XMLHttpRequest(); xmlhttp.onrea ...

extract objects from an array of objects based on a specified array

Within my JSON array, I have data structured like this: const data = [ { "uniqueId": 1233, "serviceTags": [ { "Id": 11602, "tagId": "FRRRR", "missingRequired&quo ...