使用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/2017My 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>
更多推荐
发布评论