[英]Getting the last day of a date's current quarter using moment.js
I have a javascript date such as 05-04-2020.我有一个 javascript 日期,例如 05-04-2020。
I am trying to figure out how to get the current quarter of that date and then the last day of that quarter.我想弄清楚如何获得该日期的当前季度,然后是该季度的最后一天。 The answer in this case should be 06-30-2020.
在这种情况下,答案应该是 06-30-2020。
Below is a function that I created, but have a feeling it isn't the best way to do it:下面是我创建的一个函数,但感觉这不是最好的方法:
function getLastDayOfQuarterMonth(date) {
let retVal
const quarter = moment(date).quarter()
switch(quarter) {
case 1:
retVal = new Date(moment(date).year(), 2, 31)
break;
case 2:
retVal = new Date(moment(date).year(), 5, 30)
break;
case 3:
retVal = new Date(moment(date).year(), 8, 30)
break;
case 4:
retVal = new Date(moment(date).year(), 11, 31)
break;
}
return retVal
}
We can make use of quarter
and endOf
methods provided by moments
.我们可以利用的
quarter
和endOf
提供方法moments
。
const date = "05-04-2020"; const getLastDayOfTheQuarter = (date) => moment().quarter(moment(date, "MM-DD-YYYY").quarter()).endOf('quarter').format("MM-DD-YYYY"); console.log(getLastDayOfTheQuarter(date)); console.log(getLastDayOfTheQuarter(moment().format("MM-DD-YYYY")));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
For simplicity, I have considered the input and output format as MM-DD-YYYY
.为简单起见,我将输入和输出格式视为
MM-DD-YYYY
。 It can be updated as per the need.它可以根据需要进行更新。
You can simple use endOf("quarter")
:您可以简单地使用
endOf("quarter")
:
function getLastDayOfQuarterMonth(date) { return moment(date, "MM-DD-YYYY").endOf('quarter').toDate(); } console.log(getLastDayOfQuarterMonth("05-04-2020"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.25.0/moment.min.js"></script>
Please note that you have to specify format to correctly parse 05-04-2020
in moment, see moment(String, String)
.请注意,您必须指定格式才能在瞬间正确解析
05-04-2020
,请参阅moment(String, String)
。 You can use toDate()
to get a copy of the native Date object that Moment.js wraps or format()
to get the output you prefer.您可以使用
toDate()
获取 Moment.js 包装的本机 Date 对象的副本,或使用format()
获取您喜欢的输出。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.