最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Last day of selectected quarter - Stack Overflow

programmeradmin5浏览0评论

I am using the following function to find the last day of quarter of selected day. Now I am just adding 12*Date.WEEK but is not exactly what I want. Could you please have look and advice how to find the last day of quarter? I want to have the last day of quarter in date2.

 function catcalc(cal) { 
 var date = cal.date;
    var time = date.getTime(); 
    var field = document.getElementById("x_Bis");
    if (field == cal.params.inputField) {        
        field = document.getElementById("x_Von");
        time -= 12*Date.WEEK; // substract one week
    } else {                           
     time += 12*Date.WEEK; // add one week  6*Date.DAY
    }                                        
    var date2 = new Date(time);                              
  field.value = date2.print("%d.%m.%Y");  

I should keep the function structure and keep the name of variable. There are two calendar fields which are linked to each others. The user can just select from calendar any date (no clock time is necessary). The function is ing from .0/doc/html/reference.html.

I am using the following function to find the last day of quarter of selected day. Now I am just adding 12*Date.WEEK but is not exactly what I want. Could you please have look and advice how to find the last day of quarter? I want to have the last day of quarter in date2.

 function catcalc(cal) { 
 var date = cal.date;
    var time = date.getTime(); 
    var field = document.getElementById("x_Bis");
    if (field == cal.params.inputField) {        
        field = document.getElementById("x_Von");
        time -= 12*Date.WEEK; // substract one week
    } else {                           
     time += 12*Date.WEEK; // add one week  6*Date.DAY
    }                                        
    var date2 = new Date(time);                              
  field.value = date2.print("%d.%m.%Y");  

I should keep the function structure and keep the name of variable. There are two calendar fields which are linked to each others. The user can just select from calendar any date (no clock time is necessary). The function is ing from http://cimanet.uoc.edu/logica/v2/lib/jscalendar-1.0/doc/html/reference.html.

Share Improve this question edited Jan 20, 2014 at 13:35 mplungjan 179k28 gold badges182 silver badges240 bronze badges asked Jan 19, 2014 at 17:49 user727198user727198 891 gold badge2 silver badges11 bronze badges 3
  • 1 Why the calculation? if date < mar 31, last day = mar 31, else if < June 30, last day = june 30 and so on – mplungjan Commented Jan 19, 2014 at 18:05
  • You mean just check the date and put some if or switch? But how can store the last day to time? – user727198 Commented Jan 19, 2014 at 18:31
  • I think my new code is more elegant now :) – mplungjan Commented Aug 27, 2022 at 19:41
Add a ment  | 

4 Answers 4

Reset to default 3

Updated Aug 2022

Using the fact that the 0th day of the next month in JS is the last day of current month. Note that months start at 0 so month 3 is April and the 0th of April is March 31

const getQ = date => {
  const t = new Date(date.getTime()), year = t.getFullYear() // copy
  t.setHours(0, 0, 0, 0); // normalise before using
  return [3, 6, 9, 12].map(month => new Date(year, month, 0)).find(q=>t<=q)
};


// testing
const output = document.getElementById("output");
let d, q, dates = [new Date(2022, 2, 31, 23, 59), new Date(2022, 4, 31, 23, 59), new Date(2022, 9, 31, 23, 59) ];
output.innerHTML = dates
  .map(d => `${getQ(d).toLocaleDateString()} the end of the quarter containing ${d.toLocaleDateString()}`)
  .join("<hr/>");
<div id="output"></div>

But actually is the calculation from Balage the simplest so far.

Here in a function since he did not bother

const getQ = date => {
  let quarter = Math.floor((date.getMonth() / 3)), startDate = new Date(date.getFullYear(), quarter * 3, 1);
  return [startDate, new Date(startDate.getFullYear(), startDate.getMonth() + 3, 0)]
};

const output = document.getElementById("output");
let d, q, dates = [new Date(2022, 2, 31, 23, 59), new Date(2022, 4, 31, 23, 59), new Date(2022, 9, 31, 23, 59) ];
output.innerHTML = dates
  .map(d => {
    q = getQ(d);
    return `${q[0].toLocaleDateString()} is the start and ${q[1].toLocaleDateString()} the end of the quarter containing ${d.toLocaleDateString()}`;
  })
  .join("<hr/>");
<div id="output"></div>


Old version

Live Demo

function getQ(date) {
  var t=new Date(date.getTime()),year=t.getFullYear() // copy
  t.setHours(0,0,0,0); // normalise to not get boundary errors
  // note months start at 0 in  JS
  var q1 = new Date(year,2,31),
      q2 = new Date(year,5,30),
      q3 = new Date(year,8,30),
      q4 = new Date(year,11,31);
  if (t<=q1) return q1;
  if (t<=q2) return q2;
  if (t<=q3) return q3;
  if (t<=q4) return q4;
}
getQ(new Date()); // today will return 31st of March

In your code, I would guess you can use

function catcalc(cal) { 
  var date = cal.date;
  var field = document.getElementById("x_Bis");
  if (field == cal.params.inputField) {        
    field = document.getElementById("x_Von");
  }                                        
  var date2 = getQ(date);
  field.value = date2.print("%d.%m.%Y");  
}

Expanding @mplungjan proposal (and minding the JavaScript dumbness when working with dates). I'll use method chaining, so every next method will operate on what previous method have returned.

function getLastDayOfQuarter(date) {
  var year = date.getFullYear();
  var quarterEndings = [[3, 31], [6, 30], [9, 30], [12, 31]];

  var toDateObj = function (dates) {
    return new Date(year, dates[0] - 1, dates[1]);
  };

  var isBeforeEndDate = function (endDate) {
    return endDate >= date;
  }

  date.setHours(0, 0, 0, 0);

  return quarterEndings
    .map(toDateObj)
    .filter(isBeforeEndDate)[0];
}

getLastDayOfQuarter(new Date()).toDateString(); // "Mon Mar 31 2014"

Demo: http://jsbin./eZoliye/1/edit?js,console

This may be simpler than other answers. Gives you first and last date of current quarter. Works with other arbitrary dates if you change the first line.

let now = new Date();
let quarter = Math.floor((now.getMonth() / 3));
let startDate = new Date(now.getFullYear(), quarter * 3, 1);
let endDate = new Date(startDate.getFullYear(), startDate.getMonth() + 3, 0);

console.log(startDate, endDate);

var sDate = '2024-1-25';
var today = new Date(sDate); // or just new Date()
var quarter = Math.floor((today.getMonth() / 3)) + 1;
var firstDateAfterCurrentQuarter = new Date(today.getFullYear(), quarter * 3, 1);
var lastDateOfQuarter = new Date(firstDateAfterCurrentQuarter - 1);
发布评论

评论列表(0)

  1. 暂无评论