2016-09-06 91 views
2

我在项目中使用momentJS,我有一个函数需要monthyear,并使用这些参数返回月份的最后一天。瞬间JS月份的最后一天

一切工作正常,1至11月,并尽快,因为我用月,它返回月份。

任何想法,我可以调整这个工作?我传递真实的月份值(5 = 5月),然后在该函数中减去一个月,使其基于时刻才能正常运行。

小提琴: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()) 

回答

5

相反的:

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

这样做:

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

基本上,你不想在错误的点,然后移动到开始一个月后,你只需要从正确的角度开始。

+0

完全是有道理的,没赶上那一个 - 谢谢! – SBB

1

您可以分析与格式的日期,然后瞬间就会正确地解析日期,而不需要在一个月中减去。我认为这是更具可读性到底

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>

相关问题