Creating an array of future dates using Moment.js

I am trying to use moment.js to create an array of the next 12 months, starting from the current month. For example, let's say the current month is December:

var monthsArray = [
  "December",
  "January",
  "February",
  "March",
  [...]
  "November"
  ]

However, my current implementation simply lists all 12 months of a year without taking into account a specific starting month.

var count = 0;
var months = [];
while (count < 12) 
  months.push(moment().month(count++).format("MMMM"));

I believe I can determine the user's current month with:

_private.userMonth = moment().format('MMMM');

Could someone help me figure out how to modify this code to generate an array of months starting from the current month?

Answer №1

Consider this method, among the various approaches available.

let weekdays = moment.weekdays();
let upcomingWeekdays = weekdays.concat(weekdays.slice(0, moment().day())).slice(-7);

// ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]

While not the most elegant solution, it gets the job done efficiently. For a discussion on how to properly rotate an array in JavaScript, check out this thread here.

Answer №2

To incorporate a specific future date, you can utilize the `add` feature in moment:

let interval = 0;
let upcomingMonths = [];
while (interval < 12) {
  upcomingMonths.push(moment().add(interval++, 'month').format('MMMM'));
}

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

Utilize PHP server to serve index.html for all routes with the combination of React and react-router-dom

Usually, I develop websites using a combination of reactjs, node, and express, then deploy them to Heroku. Everything works smoothly with this setup. However, I recently received a request to create a reactjs frontend with a PHP backend and deploy it to c ...

What measures can be taken to keep the rightmost element from moving when hovered over?

While I am generally happy with the layout, there seems to be a slight jump to the left when hovering over the right-most image (you need to click "show images" to view them). Strangely, this issue does not occur with the last row of images. Any suggestion ...

Sending reference variable from Angular input type=file

I am currently learning Angular and I have implemented a feature where a list of PDF files is displayed using an array called pdfs. In my template, these PDF files are parsed into "card" elements for better visualization. The issue arises when I attempt ...

Exploring Angular.js: Finding the correct path in a JSON array

Within my Angular application, I have a $scope variable defined as follows. $scope.roleList2 = [ { "roleName" : "User", "roleId" : "role1", "children" : [ { "roleName" : "subUser1", "roleId" : "role11", "collapsed" : true, "children" : [ ...

Convert a Twitter Direct Message Link by changing the `<button>` tag to an `<a>` tag

When you log into Twitter and have Direct Message enabled, a "Send Message" button will appear. Can someone please provide the URL for sending a DM to a specific user? I tried looking at the code but I could use some assistance. Any thoughts? Thank you in ...

Ways to eliminate the dotted line from the image map in Internet Explorer 11

Below you will find the code I am working with: <img alt="Testing 2015" border="0" src="images/Test-2015.jpg" usemap="#Map" /> <p><map name="Map"><area coords="790,100,653,135" href="http://www.google.com/" shape="rect" style="cursor ...

What is the best way to transfer data from a parent component to a child component in ReactJs?

When dealing with nested react elements, how can you pass values from the parent element to a child element that is not directly inside the parent element? React.render( <MainLayout> <IndexDashboard /> </MainLayout>, document.b ...

Iterate through all elements in Javascript/jQuery while excluding any nested children elements

Looking to retrieve all elements in the document: $("*").each(function(){ var el = $(this); }); I want to target only parent elements, excluding their children. For example: <div> <!--TARGET--> <div></div> <!--IGNORE--&g ...

How does Mongoose handle returning objects internally?

I have a story that might be a bit tedious, but I was really puzzled by this issue. Here's the scenario: I was attempting to modify the value of the article object returned by the Mongoose static Model method in my service layer. This is what the ob ...

Using a semicolon right after "id" is recognized as an unexpected token

I encountered an issue while attempting to run my express.js program. The main server fails to start and displays the following error message. id; ^ SyntaxError: Unexpected token ; at new Script (vm.js:80:7) at createScript (vm.js:274:10) ...

What steps can be taken to eliminate the useSearchParams() and Suspense deployment error?

I'm encountering an issue where ⨯ useSearchParams() needs to be enclosed within a suspense boundary on the page "/PaymentPage". More information can be found at: https://nextjs.org/docs/messages/missing-suspense-with-csr-bailout Although I have wra ...

Can we save javascript-generated HTML audio as a file on the back-end server?

In my latest project, I am building a JavaScript sequencer that controls HTML audio using intervals and timeouts. The goal is to handle all the processing and recording on the back-end while displaying a "Processing..." message to the user, and then utili ...

an observable with an empty array inside

I am working with a ko.observable that holds an object containing three arrays structured like this: self.filter({ file: [], site: [], statut: [] })` However, my attempts to empty these arrays have been unsuccessful. I have tried using the code: array = ...

Tips on submitting an HTML form, utilizing ajax for processing, and showcasing PHP variable within a DIV on the current page

After struggling for over 6 hours, I've finally mustered up the courage to ask this question. My eyes are practically crossed from all the effort! Despite having some experience with PHP and HTML, Ajax and jQuery are completely new territories for me ...

Failure to properly evaluate the ID string in Express

I'm currently developing an express app and I am facing an issue with adding a friends list on a user's profile page. The user has an array of friends, which is essentially an ID pointing to another user. However, when comparing this ID to the us ...

Error: The function $(...).live is not defined within the MVC framework

I included a dialog box using jQuery in my MVC form. Here is the code snippet from my View : <link rel="stylesheet" href="//code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css"> <script src="//code.jquery.com/jquery-1.10.2.js"></scr ...

Extracting data from a nested JSON array within an AngularJS template

Here is some JSON data: { "tracks": [ { "album": { "released": "2013", "href": "spotify:album:3qGeRY1wt4rrLIt1YuSwHR", "name": "The Marshall Mathers LP2 (Deluxe)", "availability": { ...

Implement Vue.js functionality to dynamically add the 'active' class upon clicking an element, while also removing

Is it possible to create an active link on a div element? Check out this example to see how you can achieve that in your code: http://jsfiddle.net/fiddleyetu/9ff79/ $(function() { $( 'ul.nav li' ).on( 'click', function() { $ ...

Retrieving JSON data in Angular 2

There are limited options available on SO, but it seems they are no longer viable. Angular 2 is constantly evolving... I am attempting to retrieve data from a JSON file in my project. The JSON file is named items.json. I am pondering if I can achieve th ...

Looking to design an interactive grid for generating dynamic thumbnails

I am a beginner in the field of web development and I have a desire to create a website for showcasing my portfolio. This website should feature project thumbnails along with brief descriptions, all of which should be displayed dynamically. Although I poss ...