How can I retrieve the current quarter, as well as the three preceding quarters, including the corresponding year, using Moment.js

Could you provide a method for retrieving the current quarter and the previous three quarters in conjunction with the year? For instance, it should output four quarters as follows:

q3-2016 q2-2016 q1-2016 q4-2015

Answer №1

Check out this efficient solution using Moment.js:

const moment = require('moment');

let fmt      = '[q]Q-Y';
let quarters = [
  moment().format(fmt),
  moment().subtract(1, 'Q').format(fmt),
  moment().subtract(2, 'Q').format(fmt),
  moment().subtract(3, 'Q').format(fmt)
];
// The resulting array is [ 'q3-2016', 'q2-2016', 'q1-2016', 'q4-2015' ]

If you prefer a more concise version, here is an alternative approach:

let quarters = [ 0, 1, 2, 3 ].map(i => 
  moment().subtract(i, 'Q').format('[q]Q-Y')
)

Answer №2

let currentDate = new Date();
    let year = currentDate.getFullYear();
    let month = currentDate.getMonth();
    let quarter = Math.floor(month / 3) + 1;
    let result = "";
    for (let i = 0; i < 4; i++) {
        result += "q" + quarter + "-" + year;
        if (i < 3) {
            result += " ";
            quarter--;
        }
        if (quarter == 0) {
            quarter = 4;
            year--;
        }
    };
console.log(result);

Answer №3

To tackle the concept of calendar quarters, you can follow an approach like Jeremy's or take a more creative route using array methods. The code snippet below demonstrates a slightly different method to calculate quarters.

If your definition of "quarter" varies (such as Q1 being Jul-Sep inclusive for financial purposes), adjust the initial value of q accordingly.

function determineQuarters() {
  var currentDate = new Date().toISOString().split('-').splice(0,2);
  var currentQuarter = Math.ceil(currentDate[1] / 3);
  return new Array(4).fill(null).reduce(function(acc, v,i, arr) {
    arr[i] = 'q' + currentQuarter + '-' + currentDate[0];
    currentDate[0] -= currentQuarter == 1 ? 1 : 0;
    currentQuarter -= currentQuarter > 1 ? 1 : -3;
    return arr;
  }, null);
}

console.log(determineQuarters())

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

IE and Firefox display different responses when encountering an empty XML document

When working with jQuery to read an XML file, I occasionally encounter the situation where the XML is empty. In this case, I anticipate that the error function (no_info) will be triggered because the file is not formatted as expected for the dataType. Int ...

Tips for Passing Parameters to Vuex mapActions correctly:Executing mapActions in Vuex requires a specific

I am facing an issue with my ProjectPage.vue where I display project issues in a v-data-table. The projects are fetched from a server API call in the sidebar and displayed there. Once I select a project, I want to use its id to retrieve its corresponding i ...

Creating dynamic bar chart visuals using Morris.js with JSON responses

Utilizing the morris.js library, I am extracting and plotting bar charts from data retrieved through a webservice. Issue: The format of my webservice URL is as follows: http://localhost:9999/hellowebservice/search?select=* I populate the select query ...

Incorporating MediaElement.js into an AngularJS environment

I am encountering an issue with a simple audio setup for mediaElement.js. It functions correctly with normal HTML/Js, but fails to work when implemented in AngularJS. The media player is displayed without any problems, however, when clicking the play butto ...

Extract the JSON file data by eliminating the indexes (1,2,3..) and transforming it into an array format

Here is the content from the JSON file: { "1": { "Order Number": "CA-2017-126221", "Order Status": "Completed", "Order Date": "30/12/2017", "First Name (Billing)": "Abdul", "State Code (Shipping)": "SD", ...

Retrieve a PHP file utilizing Javascript or JQuery

Is there a more straightforward method than using ajax to retrieve the contents of an HTML or PHP file and place it within a div on the current page? I am familiar with the process through ajax, but I am curious if there is a simpler alternative that doe ...

Determining if a path is within the same directory: a step-by-step guide

I need to check if the input path is located in the same folder or not Question: Is the input path in the same folder? For example, if my current path is f://learning/java and I am currently in a folder named java, then any path that directly belongs to ...

Iterate through the array and display each element

I am facing an issue with looping through an array in JavaScript/jQuery and printing the values to the console. Even though it seems like a simple task, I am unable to make it work. Currently, I have only one value in the array, but I believe adding more v ...

Deactivate background hover effects for bar charts in Recharts

Is there a way to disable the gray background that appears when hovering over bar charts in Recharts? I'm using version 1.4.1 and my code looks like this: import React from "react" // Recharts import { Bar, BarChart, CartesianGrid, ResponsiveContain ...

Guide to implementing setTimeout in a .map() function in ReactJS

I am currently working on a project that involves an array of players. Whenever a user adds a new player to this array, I need it to be displayed one at a time with a 500ms interval between each player. Below is the code snippet I have written for this f ...

What is the most effective way to implement a single modal throughout my web application without having to duplicate HTML code on each page?

After realizing I was repetitively adding the same div to every page for a modal dialog, I decided to place a single div in the site.master page and call it when needed. This method worked fine until I began implementing ajax with partial page updates. H ...

The transformation of a class-based component into a functional one is proving to be ineffective

I am attempting to transform my class-based component into a functional one, but I am struggling with passing two parameters in one onClick function without relying on set state. Additionally, I want to avoid creating multiple extra functions as it would i ...

Advanced filtering of arrays in JavaScript

The data structure I am working with consists of nested arrays of objects, each containing further nested arrays ad infinitum. Imagine deep nesting levels. Let me illustrate my goal with an example. I have a collection of groups. Each group contains heroe ...

How can I retrieve the elements that have been removed using $pull in mongoose?

Currently, I am utilizing $pull to eliminate a subdocument from an array within a document. It may be pertinent to note that the subdocuments in my case contain _id and are therefore indexed. Here is the JSON schema description: user: { _id: Strin ...

At what point are DOMs erased from memory?

Recently, I've been working on an application that involves continuous creation and removal of DOM elements. One thing I noticed is that the process memory for the browser tab keeps increasing even though the javascript heap memory remains steady. To ...

angularjs bootstrap typeahead result offspring

I have a situation where my input is bound to the object line.product, but the typeahead function is returning pairs of products and suppliers. The current code ps.product as ps.product.code for ps in getProductSupplierRefList($viewValue) does not return t ...

AngularJS, the element being referenced by the directive is empty

Currently, I am in the process of transferring a jQuery plugin to AngularJS simply for the enjoyment of it. Previously, when working with jQuery, my focus was on manipulating the DOM using jQuery functions within the plugin loading function. Now that I am ...

Exploring the concept of data sharing in the latest version of Next.JS - Server

When using App Router in Next.JS 13 Server Components, the challenge arises of not being able to use context. What would be the most effective method for sharing data between various server components? I have a main layout.tsx along with several nested la ...

Is it possible to transfer a URLFetchApp.fetch request from the Google Apps Script side to the JavaScript side?

My current task involves parsing an XML document tree upon clicking a button. The XML file is obtained using a lookup function that requires two values ("id" and "shipping") to be inserted into the appropriate URL. Then, the data retrieved is parsed using ...

Tips for using the identical function on matched elements

I am working on a code where I want each textbox input to change its corresponding image. The function is the same for all partners in the list (txt & img). I have looked around and found some similar posts, but I am struggling to make the function wor ...