简体   繁体   English

使用moment.js将日期设置为第一天

[英]Setting the day of the date to the 1st with moment.js

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 今天的日期: 21/05/2017
  • startDate = 01/04/2017 startDate = 01/04/2017
  • endDate = 30/06/2017 endDate = 30/06/2017

My code: 我的代码:

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

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. 只需使用addsubtract获得下个月和上个月,并使用startOfendOf获得该月的第一天和最后一天。

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> 

您可以使用moment().startOf('month')moment().endOf('month')方法

let startDate = moment().startOf('month').subtract(1, 'months').toDate()
let endDate = moment().endOf('month').add(1, 'months').toDate()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM