使用moment.js将日期的日期设置为1st(Setting the day of the date to the 1st with moment.js)

编程入门 行业动态 更新时间:2024-10-23 10:24:35
使用moment.js将日期的日期设置为1st(Setting the day of the date to the 1st with moment.js)

我正在查看文档的时刻,无法找到所需的方法。 在我的解决方案中,我得到今天的日期然后获得前一个月和后一个月,但希望得到月的第一天和前一个月的最后一天。

简而言之,这应该是出来的:

今天的日期: 21/05/2017 startDate = 01/04/2017 endDate = 30/06/2017

我的代码:

var startDate = moment(date).subtract(1,'months') var endDate = moment(date).add(1,'months');

I am looking through the moment documentation and can't find the the method required. In my solution I am getting today's date then getting the month before and the month after, but wish to get the very first day of the month and the very last day of the month ahead.

In brief this should be the out come:

today's date: 21/05/2017 startDate = 01/04/2017 endDate = 30/06/2017

My code:

var startDate = moment(date).subtract(1,'months') var endDate = moment(date).add(1,'months');

最满意答案

只需使用subtract法获取下一个月和上个月,使用startOf和endOf获取该月的第一天和最后一天。

这是一个工作样本:

var date = moment([2017, 4, 21]); // one way to get 21/05/2017
// If your input is a string you can do:
//var date = moment('21/05/2017', 'DD/MM/YYYY');
var startDate = date.clone().subtract(1, 'month').startOf('month');
var endDate = date.clone().add(1, 'month').endOf('month');

console.log(startDate.format('DD/MM/YYYY')); // 01/04/2017
console.log(endDate.format('DD/MM/YYYY'));   // 30/06/2017 
  
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script> 
  
 

Simply use add and subtract method to get next and previous month and startOf and endOf to get the first and the last day of the month.

Here a working sample:

var date = moment([2017, 4, 21]); // one way to get 21/05/2017
// If your input is a string you can do:
//var date = moment('21/05/2017', 'DD/MM/YYYY');
var startDate = date.clone().subtract(1, 'month').startOf('month');
var endDate = date.clone().add(1, 'month').endOf('month');

console.log(startDate.format('DD/MM/YYYY')); // 01/04/2017
console.log(endDate.format('DD/MM/YYYY'));   // 30/06/2017 
  
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script> 
  
 

更多推荐

本文发布于:2023-07-23 18:44:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1235695.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:日期   设置为   js   moment   date

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!