Determining the month and year by considering the duration

Given the available data of month, year, and duration, the task is to iterate through the months for the specified duration and determine the month at the end of that period.

For instance, If the chosen month is March 2015 and the duration is 4 months, the desired outcome would be November 2014 - which is 4 months prior to the selected month.

How can this be best achieved?

Answer №1

momentjs is a great tool for handling date and time in JavaScript:

let currentDate = new Date;
let threeWeeksAgo = moment(currentDate).subtract(3, 'weeks');

If your dates are in the format "Apr 2021", you can easily create a date object using

let yourDateObject = moment('Apr 2021')

Answer №2

Here is how you can achieve a similar result:

function updateDate(initialDate, months){
   var date = new Date(initialDate);
   date.setMonth(date.getMonth() + months);
   return date;
}

The parameter months indicates the number of months to add or subtract from the initial date. This code uses plain JavaScript and does not require any additional libraries.

For example:

updateDate('Mar 2015', -4);

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

add to array object if it does not already exist

I am currently working with the following model in JavaScript and utilizing AngularJS: $scope.data = { FocusOn: " ", Filters: [], Range: { From: "", To: "" } } Additi ...

React Native NavigationStack encountering mismatched screen component types

Currently, I am in the process of developing an app using React Native and React Navigation, utilizing TypeScript. One important step I took was creating a type called RootStackParams for my routes as shown below: App.tsx export type RootStackParams = { ...

The "discord.js" module is throwing an error stating that the property for

Currently, I am in the process of developing a Discord bot using discord.js. As part of this project, I am incorporating JSON functionality to store information for individual users in a separate file. However, I have encountered an issue where an error me ...

Transmit JSON information using jQuery

Can you explain why the code below is sending data as City=Moscow&Age=25 instead of in JSON format? var arr = {City:'Moscow', Age:25}; $.ajax( { url: "Ajax.ashx", type: "POST", data: arr, dataType: 'js ...

Prefixes for logging - Consider using the not-singleton technique or another approach

I am currently developing a logging helper for Node.JS that includes several exported functions such as error and warn. For instance, I have two other scripts called test1 and test2 which make use of this "module". When initializing my logging module us ...

Enrich an HTML table using jQuery based on an indentation pattern

                 Overview: Currently, my colleague and I are working on developing an inventory control system using the Django Framework within our department. While most aspects of the system are operational, we are encountering ...

The API is returning a successful response code of 200 when the HEAD and OPTIONS methods are utilized

My API is up and running smoothly with a GET method in express. This is the code for my API: app.get('/healthcheck', (_req, res) => { res.status(200).send({ state: 'Healthy', timestamp: new Date(), uptime: process.upti ...

Tips for Filling Kendo Dropdown with JSON Data

I'm facing an issue with populating a Kendo dropdown using AJAX JSON response. The dropdown list is showing up blank. Can anyone point out what I might be missing here? Your help would be greatly appreciated. Here's the corresponding HTML code: ...

What is the best way to send a response containing an array of JSON objects in node.js?

Is there a way to retrieve an array of completed pivotal stories using the pivotal-node module for node.js? app.get('/delivered_stories', function(request, response) { pivotal.useToken("my_token"); pivotal.getProjects(function ( ...

What is the best way to implement automatic scrolling to the bottom of a materialUI drawer in React after a page refresh?

I am facing an issue with my Material UI Drawer, which contains numerous checkboxes and radio buttons for an advanced search page. Whenever a checkbox or radio button is clicked, it triggers an API request to fetch results instantly without requiring a sub ...

Is there a way to retrieve the current state value during the `beforeunload` event when refreshing the page?

import React, { useState, useEffect } from "react"; import "./styles.css"; export default function App() { const [counter, setCounter] = useState(0) useEffect(() => { const intervalID = setInterval(() => { setCounter(prevCounter => ...

Tips for optimizing HTML (Jade template) to utilize *.min JavaScript and CSS files for production purposes

Utilizing Grunt for the compilation of jade templates into HTML, as well as uglifying/concatenating JS and minimizing/concatenating CSS. During the development process, I employ a combination of connect and watch to serve the front-end and automatically d ...

Does the notion of "Execution context and the stack" only pertain to web browsers?

Does the concept of "Execution context and the stack" only apply to browsers, or is it also utilized in other environments such as NodeJS? I've crafted 2 statements but unsure if they are accurate: 1- "The environment for JavaScript is not solely the ...

Using express version 4.x to send an empty JSON object

I'm struggling with returning an object in JSON format using Express. What's confusing me is the following code snippet: class Greeting { Greeting(name) { this.name = name; } get name() { return name; } } app.get('/json/:na ...

What is the reason behind Angular's refusal to automatically bind data when an object is cloned from another object?

Check out this simple jsfiddle I made to demonstrate my question: fiddle Here is the HTML code snippet: <div ng-controller="MyCtrl"> <div ng-repeat="p in products"> <span ng-click="overwrite(p)">{{ p.id }}: {{ p.name }}& ...

How can I adjust the radius of the Google Places service in real-time?

When I input a value such as 1000 in the text field, I want to dynamically change the radius in the request variable. For example, if I enter 1000 meters, only parking areas within that radius should be visible. Similarly, entering another value should d ...

When trying to run the "npm start" command, I encountered a syntax error that specifically mentioned the use of

Every time I attempt to run the npm start command, I encounter the following error: I have followed the steps provided in this link: https://github.com/kriasoft/react-starter-kit/blob/master/docs/getting-started.md Could you please advise on how to resolve ...

Customize Bootstrap layout on the fly

I have encountered a slight dilemma. I am attempting to implement something similar to the following: <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/> <script src="https://ajax.googleapis.com ...

Using VueJS to dynamically load a separate component into a Vue instance

Currently, I am working on revamping our web platform at my job. This includes migrating a significant amount of outdated JavaScript/jQuery code to VueJS. We have a "global.js" file that contains our Vue components and a "vendor.js" file that includes Vue ...

Transferring files via Bluetooth on PhoneGap

As someone new to phonegap, I'm interested in transferring text files from one device to another using Bluetooth within the platform. I've looked at several examples but haven't found a solution yet. I've come across some examples that ...