Finding the start and end dates of a specific month using Moment JS

I am facing an issue with calculating a JS date for the year 2014 and month 9 (September 2014).

My attempted solution was:

var moment = require('moment');
var startDate = moment(year + '-' + month + '-01' + ' 00:00:00');
            var endDate = startDate.endOf('month');
            console.log(startDate.toDate());
            console.log(endDate.toDate());

However, both logs are displaying:

Tue Sep 30 2014 23:59:59 GMT+0200 (CEST)
Tue Sep 30 2014 23:59:59 GMT+0200 (CEST)

The end date is correct but I am puzzled as to why the start date is not accurate.

Answer №1

One reason for this behavior is that the endOf function in Moment.js modifies the original value.

Explaining further:

The original moment object is changed to represent the end of a specified unit of time.

Below is a sample function that can help you achieve the desired result:

function getMonthDateRange(year, month) {
    var moment = require('moment');

    // as months are zero-based in moment.js (i.e., January is 0), subtracting one from user input
    var startDate = moment([year, month - 1]);

    // Creating a clone of the start date before using .endOf() method 
    var endDate = moment(startDate).endOf('month');

    // Outputting the dates for demonstration purposes:
    console.log(startDate.toDate());
    console.log(endDate.toDate());

    // Remember to convert to plain JavaScript Date type by calling toDate()
    return { start: startDate, end: endDate };
}

Additional Resources:

Answer №2

Here is a simple way to get the start or end date of the month:

const startDate = moment().startOf('month').format("YYYY-DD-MM");
const endDate = moment().endOf("month").format("YYYY-DD-MM");

If you want to customize the format, just define it in the code.

Answer №3

By utilizing the .endOf() method, you are actually modifying the object it is applied to, causing the startDate variable to change to Sep 30.

To prevent this from happening, it is recommended to use the .clone() method to create a duplicate instead of altering the original object.

var startDate = moment(year + '-' + month + '-' + 01 + ' 00:00:00');
            var endDate = startDate.clone().endOf('month');
            console.log(startDate.toDate());
            console.log(endDate.toDate());

Mon Sep 01 2014 00:00:00 GMT+0700 (ICT) 
Tue Sep 30 2014 23:59:59 GMT+0700 (ICT) 

Answer №4

Check out this code snippet:

const time=require('time');
console.log("start=>",time().startOf('day').format("YYYY-DD-MM"));
console.log("end=>",time().endOf('day').format("YYYY-DD-MM"));

Answer №5

While there may not be a direct method to obtain the last day of the month, you can achieve this by following these steps:

let currentDate = new Date();
/**
 * By adding 1 month to the current date and then subtracting 1 day,
 * we can find the last day of the present month.
 */
currentDate.setMonth(currentDate.getMonth() + 1);
currentDate.setDate(0);
/* Displaying the date of the last day of the month */
console.log(currentDate.toLocaleDateString());

Answer №6

To determine the end date based on a given start date that is set as the first day of the month, you can use the following code:

let endDate = moment(startDate).add(1, 'months').subtract(1, 'days');

I trust this information proves beneficial to you!

Answer №7

let currentDate = new moment();
let beginningOfMonth = currentDate.clone().startOf('month');
let endOfMonth = currentDate.clone().endOf('month');
console.log(beginningOfMonth, endOfMonth);

documentation

Answer №8

let year = 2014;
let month = 9;

// adjusting for zero-based indexing in momentjs
let startDate = moment([year, month - 1, 01]).format("YYYY-MM-DD");

// calculating the number of days in the selected month
let daysInMonth = moment(startDate).daysInMonth();

// determining the end date by adding days to the start date
let endDate = moment(startDate).add(daysInMonth - 1, 'days').format("YYYY-MM-DD");

console.log(`start date: ${startDate}`);
console.log(`end date:   ${endDate}`);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js"></script>

Answer №9

const dateList = retrieveDatesInRange("2014-05-02", "2018-05-12", "YYYY/MM/DD", 1);           
console.log(dateList);
// receive complete date ranges based on input
var startDatesOnly = dateList.map(dateObject => dateObject["to"]);
console.log(startDatesOnly);
// additionally, if you only need starting dates then use the "map" function

function retrieveDatesInRange( startDate, endDate, format, increment ) {
    startDate = moment(startDate, format);
    endDate = moment(endDate, format);

    let dates = [];
    let from = startDate.clone();
    let to = from.clone().add(increment, "month").startOf("month").add(-1, "day");
    do {
        dates.push({
            "from": from.format(format),
            "to": ( to < endDate ) ? to.format(format) : endDate.format(format)
        });
        from = moment(to, format).add(1, "day").clone();
        to = from.clone().add(increment, "month").startOf("month").add(-1, "day");
    } while ( from < endDate );
    return dates;
}

Please remember, .clone() is crucial in momentjs to avoid value overwriting. This seems important in your scenario.

This approach is more versatile for obtaining a series of dates within a specific range.

Answer №10

Below is a succinct and precise solution:

  // Note: the month in 'moment' library starts from 0, so January is actually represented by 0, subtracting 1 accounts for this discrepancy.
  var startDate = moment([year, month - 1]).format()    
  var endDate = moment(startDate).clone().endOf('month').format()

For example:

let month = 1         // Represents January   
let year = 2021  

var startDate = moment([year, month - 1]).format()

var endDate = moment(startDate).clone().endOf('month').format()

console.log(startDate)
// Output: 2021-01-01T00:00:00-07:00

console.log(endDate)
// Output: 2021-01-31T23:59:59-07:00

Answer №11

Here is the code snippet that should be functional:

$('#reportrange').daterangepicker({
                startDate: start,
                endDate: end,
                ranges: {
                    'Today': [moment(), moment()],
                    'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
                    'Last 7 days': [moment().subtract(6, 'days'), moment()],
                    'Last 30 days': [moment().subtract(29, 'days'), moment()],
                    'Current Month': [moment().startOf('month'), moment().endOf('month')],
                    'Previous Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')],
                    'January': [moment().month(0).startOf('month') , moment().month(0).endOf('month')],
                    'February': [moment().month(1).startOf('month') , moment().month(1).endOf('month')],
                    'March': [moment().month(2).startOf('month') , moment().month(2).endOf('month')],
                    'April': [moment().month(3).startOf('month') , moment().month(3).endOf('month')],
                    'May': [moment().month(4).startOf('month') , moment().month(4).endOf('month')],
                    'June': [moment().month(5).startOf('month') , moment().month(5).endOf('month')],
                    'July': [moment().month(6).startOf('month') , moment().month(6).endOf('month')],
                    'August': [moment().month(7).startOf('month') , moment().month(7).endOf('month')],
                    'September': [moment().month(8).startOf('month') , moment().month(8).endOf('month')],
                    'October': [moment().month(9).startOf('month') , moment().month(9).endOf('month')],
                    'November': [moment().month(10).startOf('month') , moment().month(10).endOf('month')],
                    'December': [moment().month(11).startOf('month') , moment().month(11).endOf('month')]
                }
            }, cb);

Answer №12

Give this code a shot:

moment(dateStart).beginningOf('months')
moment(dateStart).stopOf('months')

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

Performing an asynchronous POST request in JavaScript

Hey there, I successfully managed to implement a post request using ajax for my submit functionality. However, I am now looking to make this asynchronous to account for any delays in processing by my php file. Unfortunately, I am struggling to figure out h ...

What is the process of saving a model with @tensorflow/tfjs-node version 2?

I've been struggling with setting up the save handler to save my model. I've scoured through various platforms like stack overflow and GitHub, but haven't had any luck. Help! Any guidance would be greatly appreciated!!! :) Below is a snipp ...

Implementing dynamic form validation with ReactJS – a step-by-step guide

I have integrated the ant design library into my demo application and now I need to implement dynamic validation for mobile numbers. There are two fields in my form: Select field Input field I want to validate the input field only when the user selects ...

Is the window frozen while Ajax processes the request?

When I make an ajax request that may take a significant amount of time to process on the server-side, I want to display a loading image during the request. However, the loading image is not showing up while the ajax request is processing. var ref = create ...

Implementing dynamic AJAX functionality for dynamically generated elements using vanilla JavaScript

Currently, I am working on developing a movie information application using ajax. However, I have encountered a challenging issue that I am struggling to resolve. After creating an ajax request, I proceed to dynamically generate content and incorporate it ...

Tips for Iterating through Nested Arrays using the Inside Array in a Dynamic Way

I am facing an issue with my code as it lacks flexibility when a new array is added to the nested array, in which case the new array is not considered. My main concern is how to access the elements of each nested array simultaneously. Here's an examp ...

What is the best way to add an array to my JSON object in Javascript?

I'm currently in the process of formatting an array into a JSON object for API submission. Struggling to find the right method to transform my array into the desired structure. This is what my array looks like: data: [ ["Lisa", "Heinz", "1993-04 ...

Prevent users from clicking by using a CSS class in HTML and JavaScript

,hey there buddy 1° Can you help me figure out how to prevent click behavior using the CSS class? 2° I'm unable to add an ID to the HTML element, so I need to use the Class to achieve this. 3° None of my attempts have been successful so far. El ...

Exploring query options in jQuery for searching text using the :contains selector

Why is the if statement below not giving me the expected results? Every time it just turns the paragraph yellow, even when the word doesn't match the :contains expression. Here's the query I'm using. $(document).ready(function() { if ($ ...

What is the process for displaying the save file dialog in Safari?

I'm struggling with generating a PDF and saving it as a file in Safari using an Angular app and DocRaptor. I've tried various methods from Stack Overflow, but none seem to trigger the save file dialog. Instead, they either open the file in the cu ...

Beginner's guide to resolving AngularJS data-ng-init binding issue

I have been learning from an AngularJS tutorial that can be found at this link : http://www.youtube.com/watch?v=i9MHigUZKEM Below is a snippet of the code I am working with: <html data-ng-app=""> <body data-ng-init="names=[{'John Smith&ap ...

Incorporating an HTTP header into d3.json using queue.js

I know that I can include a header in a D3 JSON request by using the following code: d3.json("http://localhost:8080/data") .header("Application-ID", "1") However, I'm uncertain about how to add this header when utilizing queue's defer method. ...

why is my angular listing malfunctioning when I try to compare two fields?

<div ng-controller="SamsungServicesCtrl"> <ion-content> <li class="item item-checkbox" ng-repeat="item in items" > <img src="{{item.icon}}" style="float:left;height:30px;width:30px;padding-right:5px;" & ...

Encountering a Typescript issue stating "Property 'then' does not exist" while attempting to chain promises using promise-middleware and thunk

Currently, I am utilizing redux-promise-middleware alongside redux-thunk to effectively chain my promises: import { Dispatch } from 'redux'; class Actions { private static _dispatcher: Dispatch<any>; public static get dispatcher() ...

Unexpected JavaScript Bug (with jQuery)

I have an interesting code snippet that captures button clicks and then hides the existing content, revealing the content of the clicked item instead. This code is part of my init.js file along with other functionalities: $(function() { $('#conta ...

passing a text value from PHP to a JavaScript function

Trying to pass a string retrieved from the database to a JavaScript function. In my PHP code, I have: <input type="image" name="edit_me" id="edit_me" value="<?php echo $row['id']; ?>" onClick="edit_chirp(<?php echo $row['id&ap ...

Having trouble with the menu toggle button on Bootstrap 4?

When using Bootstrap 4, the breadcrumb button may not function properly when the header becomes responsive. I have ensured that Bootstrap 4 CSS and JS are included in the project. Please assist me in resolving this issue. Code: .navbar { height:100 ...

What is the reasoning behind the "open in a new tab" function triggering a GET request?

Check out this HTML tag: <a href="#" id="navBar_navBarInput_3_subNavDropdownInput_0_subNavLinkInput_0" onclick="redirectPost(4,'EntryData.aspx');">My Cool Link</a> The Javascript function "redirectPost" function redirectPost(id, ur ...

Creating a dynamic state management system for multiple Collapse components can be achieved by utilizing

I am trying to create a Collapse menu from array data, Currently, when I click on any menu all sub menus expand I believe my issue lies in not being able to set a unique "open" state for each Main menu I want to avoid assigning a "state" to accommodate ...

Can you display a simple HTML view?

I am currently working on a Node.js application with Express framework. In my project, I have a 'views' folder containing an 'index.html' file. However, upon trying to load the webpage, I encountered the following error: Error: Cannot f ...