【问题标题】:How can I get the first day of next month using Angular and Moment如何使用 Angular 和 Moment 获得下个月的第一天
【发布时间】:2019-10-20 14:56:33
【问题描述】:

我们的应用程序生成的日志存在问题。解决方案是即使选择的日期在月中,我们也需要获取下个月的第一天。

尝试阅读 Moment 上的文档,但找不到任何可能的解决方案。

var currentDate = new Date();
var start_date = new Date(); //Wed Jun 05 2019 13:23:06 GMT+0800 (Philippine Standard Time)

console.log(start_date);

start_date.setDate(start_date.getDate() - 365); //1496640186958

console.log(start_date.setDate(start_date.getDate() - 365)); //Monday, June 5, 2017 1:23:06.958 PM GMT+08:00
// this output should be July 1, 2017, how can I get the first day of next month here?

start_date = customizeDate.formatDateToString(start_date);
var end_date = dateRange.endDate;

【问题讨论】:

    标签: angular momentjs


    【解决方案1】:

    好的,我设法使用这个函数链来解决它:

    console.log(moment(1496640186958).add(1, 'months').startOf('month').format('ll'));
    

    【讨论】:

      【解决方案2】:

      这是一种可能的方法,创建一个新的日期对象,然后将月份加 1,最后将日期设置为 1:

      start_date = new Date(start_date.getFullYear(), start_date.getMonth() + 1, 1);
      

      Stackblitz

      【讨论】:

        【解决方案3】:

        您可以将其与您的自定义格式一起使用

        const startOfNextMonth = moment().add(1, 'M').startOf('month').format('YYYY-MM-DD hh:mm:ss');
        

        const startOfNextMonth = moment().add(1, 'M').startOf('month').format('YYYY-MM-DD hh:mm:ss');
        console.log(startOfNextMonth);
        <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.js"></script>

        【讨论】:

          【解决方案4】:

          您可以使用 Vanilla JavaScript 做到这一点。请注意,我添加了 if 语句来检查当前日期的月份是否为 12 月。这是为了防止出现月份“溢出”到 12 的任何问题。

          const today = new Date(); 
          let next;
          if (today.getMonth() === 11) {
            next = new Date(today.getFullYear() + 1, 0, 1);
          } else {
              next = new Date(today.getFullYear(), today.getMonth() + 1, 1);
          }
          
          console.log(next);

          【讨论】:

            猜你喜欢
            • 2017-01-09
            • 1970-01-01
            • 2012-12-12
            • 1970-01-01
            • 1970-01-01
            • 2021-02-17
            • 1970-01-01
            • 2013-02-15
            • 1970-01-01
            相关资源
            最近更新 更多