繁体   English   中英

Moment JS每月的最后一天

[英]Moment JS last day of month issue

我在项目中使用momentJS ,并且我有一个函数,该函数需要monthyear并使用这些参数返回month的最后一天。

从1月到11月,一切工作正常,而当我使用12月时,它将恢复为1月。

有什么想法可以调整它吗? 我传递了真实的月份值(5 = 5月),然后在函数中减去一个月份,使其基于0才能正常工作。

小提琴: https : //jsfiddle.net/bhhcp4cb/

// Given a year and month, return the last day of that month
function getMonthDateRange(year, month) {

    // month in moment is 0 based, so 9 is actually october, subtract 1 to compensate
    // array is 'year', 'month', 'day', etc
    var startDate = moment([year, month]).add(-1,"month");

    // Clone the value before .endOf()
    var endDate = moment(startDate).endOf('month');

    // make sure to call toDate() for plain JavaScript date type
    return { start: startDate, end: endDate };
}

// Should be December 2016
console.log(moment(getMonthDateRange(2016, 12).end).toDate())

// Works fine with November
console.log(moment(getMonthDateRange(2016, 11).end).toDate())

代替:

var startDate = moment([year, month]).add(-1,"month");

做这个:

var startDate = moment([year, month-1]);

基本上,您不想从错误的位置开始然后再移动一个月,而只是想从正确的位置开始。

您可以使用某种格式来解析日期,然后moment可以正确地解析日期,而无需减去一个月。 我认为这最终更易读

var startDate = moment(year + "" + month, "YYYYMM");
var endDate = startDate.endOf('month');

 // Given a year and month, return the last day of that month function getMonthDateRange(year, month) { var startDate = moment(year + "" + month, "YYYYMM"); var endDate = startDate.endOf('month'); // make sure to call toDate() for plain JavaScript date type return { start: startDate, end: endDate }; } // Should be December 2016 console.log(moment(getMonthDateRange(2016, 12).end).toDate()) // Works fine with November console.log(moment(getMonthDateRange(2016, 11).end).toDate()) 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.14.1/moment-with-locales.min.js"></script> 

暂无
暂无

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

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