What is the best way to calculate the number of days between today's date and the end of the current month using Moment.js?

Here's the current code snippet I am working with:

  const moment = require('moment')
    const m = moment


    const currDay = m().format('D')
    const dayOfWeek = m().format('dddd')
    const daysInMonth = m().daysInMonth()

    const startOfMonth = moment().startOf('month').format('YYYY-MM-DD hh:mm');
    const endOfMonth   = moment().endOf('month').format('YYYY-MM-DD hh:mm');

I'm looking to generate a calendar row that starts with today's date and displays the remaining days in the month so I can showcase each day using Vue.js in my HTML.

For instance: Wed 8, Thu 9, Fri 10... Fri 31.

Answer №1

It seems like the original poster might be getting caught up in the common pitfall of formatting too early. While it's helpful to format data for better readability during development, doing so prematurely can result in a string that is not suitable for further calculations.

One approach is to work with date objects directly and only convert them to strings when necessary for (a) human consumption or (b) storage and transmission purposes.

Let's continue working without any premature formatting...

const daysRemainingThisMonth = moment().endOf('month').diff(moment(), 'days');
console.log(`There are ${daysRemainingThisMonth} days remaining this month`)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

Answer №2

If you're looking for a way to calculate the difference in days between two dates, you can utilize a function that returns the last day of the month and find the variance between the dates.

function getMonthEnd(date = new Date()) {
  return new Date(date.getFullYear(), date.getMonth() + 1, 0);
}

function getMonthDaysLeft(date = new Date()) {
  return getMonthEnd(date).getDate() - date.getDate();
}
  
let d = new Date();
console.log(`There are ${getMonthDaysLeft(d)} days left in ${d.toLocaleString('en',{month:'long'})}.`);

If you need a list or array of remaining days, you can iterate over a date one day at a time and store the formatted dates in the desired format:

function getMonthDaysLeftAsList(date = new Date()) {
  let d = new Date(+date);
  // Formatter
  let f = new Intl.DateTimeFormat('en',{
    day: 'numeric',
        month: 'short'
      });
  let m = d.getMonth();
  let dayList = [];
  while (d.getMonth() == m) {
    dayList.push(f.format(d));
    d.setDate(d.getDate() + 1);
  }
  return dayList;
}

console.log(getMonthDaysLeftAsList());

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

Troubleshooting: Angular 2 View not reflecting changes after array push

I have encountered an issue with my two child components. They are both meant to share data from a json file that I load using the http.get/subscribe method. Oddly enough, when I try to push new data into the array, it doesn't seem to update in the vi ...

Learn how to dynamically switch the background image of a webpage using a button in AngularJS

Hey there, I'm currently working on incorporating interactive buttons into my website to give users the ability to customize the background. I've been experimenting with Angular to achieve this feature. So far, I've managed to change the ba ...

How do I access the content of a webpage once it has been generated using a template engine?

Currently, I am engaging in screen scraping for a website that heavily relies on JavaScript. The site utilizes a client-side templating engine to display all of its content. Initially, I attempted to use jQuery, which proved successful in the console but n ...

PHP fails to retrieve data from a JavaScript Ajax function using the FormData object (specifically, when

I'm facing an issue where my file is not being detected when I send a FormData object using AJAX and PHP code. Both the `$_FILES` array and the `$_POST` array appear to be empty. However, the browser does send the file with the AJAX request. <inpu ...

When working with Angular 2 and Typescript, a common error message that may be encountered is "TypeError

Currently diving into Angular 2 and encountered a stumbling block while attempting to create a service. Despite my efforts in finding a solution, I seem to be missing something crucial. Error: A problem arises in angular2-polyfills.js:1243 with the error ...

Preventing users from accessing the previous page via the browser back button after logging out in an AngularJS application

Currently, I have developed an angularjs web application and facing a challenge. After logout, I am looking to prevent users from navigating back to the previous page using the browser's back button. Ideally, I would like to display a customized messa ...

What is the best way to remove a selected item from an array in Vuejs when it has been clicked

I'm having trouble with my splice() method in this simple To-Do app. I want to delete a specific task by clicking a button, but the solutions I've tried from Stack Overflow aren't working for me. The items do get deleted, but only the last o ...

Is there a way to program it so that the date updates automatically?

Is there a way to update this code so that the year changes automatically each year? </div> </div> </div></div> <div class="footer"> <p>Copyright 2023 </p> <a href="#" class="go-up& ...

Displaying HTML content using Typescript

As a newcomer to typescript, I have a question regarding displaying HTML using typescript. Below is the HTML code snippet: <div itemprop="copy-paste-block"> <ul> <li><span style="font-size:11pt;"><span style="font-family ...

Retrieve the user-inputted data from an Electron BrowserView's input field

Consider this scenario where a BrowserWindow is set up with specific security settings, including enabling the webviewTag: true for project requirements. let webPrefs = { plugins: false, nodeIntegration: false, nodeIntegrationInWorker: false, ...

Is it necessary to include a request in the API route handler in Next.js when passing parameters?

In my API route handler, I have a function for handling GET requests: import { NextRequest, NextResponse } from "next/server"; export async function GET(req: NextRequest, { params }: { params: { id: string } }) { const { id } = params; try { ...

Creating a list that renders responsively using ReactJS

I'm currently working on implementing a responsive search bar that filters through a list of pure components (up to 100 components displayed at once). However, I've noticed there is a slight half-second delay between typing the first letter and s ...

When incorporating a JS React component in TypeScript, an error may occur stating that the JSX element type 'MyComponent' is not a valid constructor function for JSX elements

Currently, I am dealing with a JavaScript legacy project that utilizes the React framework. Within this project, there are React components defined which I wish to reuse in a completely different TypeScript React project. The JavaScript React component is ...

Exploring the versatility of 2D arrays in Python

Can anyone assist me in creating a dynamic 2-dimensional array in Python? I need the number of columns to be fixed, but the number of rows should be able to change dynamically. I am open to using numpy for this task. Please note that I am using Python 3, ...

Converting Dynamo DB stream data into Json format

I need to convert the DDB stream message into a standard JSON format. To achieve this, I am using unmarshalleddata = aws.DynamoDB.Converter.unmarshall(result.NewImage); where result.NewImage is { carrier: { S: 'SPRING' }, partnerTransacti ...

The jQuery $.change function is not functioning properly when used with a cloned select element

In my table, there is a button that allows you to add a new row by cloning the last one. Each row contains a <select> with a different name (0-9), all having the class .variable_priority. When clicking the button, the row clones successfully and the ...

Exploring Angular 2: Unveiling the secrets of lifecycle hooks in lazy loaded

Currently, I'm working on an application that involves lazy loaded Angular modules. I have a straightforward inquiry: Is there a way to detect an event once a module is loaded? For instance, similar to the OnInit lifecycle hook for components. I fo ...

How can I verify if a date is after the current date using Node.js?

I am struggling to set up date validation that ensures the date is after the current date. This is what I have attempted so far: Router.post('/home', [ check('due_date') .isDate() .isAfter(new Date.now()) .wi ...

Learn the process of adding values to HTML forms within ExpressJS

I am facing a challenge in injecting Javascript variable values into HTML forms on an Expression JS server. I am unsure about how to solve this issue. All I want to do is insert the values of x, y, and res into the forms with the IDs 'firstvalue&apos ...

Use a boolean value to determine the styling of multiple items simultaneously

I'm currently attempting to modify the appearance of the bars in each area (a total of 12), so that a value of 1 equates to true (displayed as green) and a value of 0 equates to false (displayed as red). This will dynamically change the color of each ...