简体   繁体   English

Moment JS每月的最后一天

[英]Moment JS last day of month issue

I am using momentJS in a project and I have a function that takes a month and year and returns the last day of the month using those parameters. 我在项目中使用momentJS ,并且我有一个函数,该函数需要monthyear并使用这些参数返回month的最后一天。

Everything is working fine, Jan - November, and as soon as I use December, it is returning January. 从1月到11月,一切工作正常,而当我使用12月时,它将恢复为1月。

Any ideas how I can tweak this to work? 有什么想法可以调整它吗? I am passing the true month value (5 = May) and then subtracting a month within the function to make it 0 based for moment to function correctly. 我传递了真实的月份值(5 = 5月),然后在函数中减去一个月份,使其基于0才能正常工作。

Fiddle: https://jsfiddle.net/bhhcp4cb/ 小提琴: 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())

Instead of: 代替:

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

Do this: 做这个:

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

Basically, you don't want to start at the wrong point and then move by a month, you simply want to start at the correct point. 基本上,您不想从错误的位置开始然后再移动一个月,而只是想从正确的位置开始。

You can parse the date with a format, then moment will parse the date correctly without the need of subtracting a month. 您可以使用某种格式来解析日期,然后moment可以正确地解析日期,而无需减去一个月。 I think it's more readable in the end 我认为这最终更易读

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