Javascript 给定月份的 JS 开始和结束时刻
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26131003/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Moment JS start and end of given month
提问by Fabio B.
I need to calculate a JS date given year=2014 and month=9 (September 2014).
我需要计算给定 year=2014 和 month=9(2014 年 9 月)的 JS 日期。
I tried this:
我试过这个:
var moment = require('moment');
var startDate = moment( year+'-'+month+'-'+01 + ' 00:00:00' );
var endDate = startDate.endOf('month');
console.log(startDate.toDate());
console.log(endDate.toDate());
Both of logs show:
两个日志都显示:
Tue Sep 30 2014 23:59:59 GMT+0200 (CEST)
Tue Sep 30 2014 23:59:59 GMT+0200 (CEST)
End date is correct but... why the start date is not?
结束日期是正确的,但是...为什么开始日期不是?
回答by klyd
That's because endOfmutates the original value.
那是因为endOf改变了原始值。
Relevant quote:
相关报价:
Mutates the original moment by setting it to the end of a unit of time.
通过将原始时刻设置为单位时间的结尾来改变原始时刻。
Here's an example function that gives you the output you want:
这是一个示例函数,可为您提供所需的输出:
function getMonthDateRange(year, month) {
var moment = require('moment');
// 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 - 1]);
// Clone the value before .endOf()
var endDate = moment(startDate).endOf('month');
// just for demonstration:
console.log(startDate.toDate());
console.log(endDate.toDate());
// make sure to call toDate() for plain JavaScript date type
return { start: startDate, end: endDate };
}
References:
参考:
回答by Shakti Jadon
you can use this directly for the end or start date of the month
您可以直接将其用于本月的结束或开始日期
new moment().startOf('month').format("YYYY-DD-MM");
new moment().endOf("month").format("YYYY-DD-MM");
you can change the format by defining a new format
您可以通过定义新格式来更改格式
回答by bakkal
When you use .endOf()you are mutating the object it's called on, so startDatebecomes Sep 30
当您使用时,.endOf()您正在改变它所调用的对象,因此startDate变为 Sep 30
You should use .clone()to make a copy of it instead of changing it
您应该使用.clone()复制它而不是更改它
var startDate = moment(year + '-' + month + '-' + 01 + ' 00:00:00');
var endDate = startDate.clone().endOf('month');
console.log(startDate.toDate());
console.log(endDate.toDate());
Mon Sep 01 2014 00:00:00 GMT+0700 (ICT)
Tue Sep 30 2014 23:59:59 GMT+0700 (ICT)
回答by Sanjay Singh
Try the following code:
试试下面的代码:
const moment=require('moment');
console.log("startDate=>",moment().startOf('month').format("YYYY-DD-MM"));
console.log("endDate=>",moment().endOf('month').format("YYYY-DD-MM"));
回答by Sandeep Gantait
Don't really think there is some direct method to get the last day but you could do something like this:
不要真的认为有一些直接的方法可以得到最后一天,但你可以这样做:
var dateInst = new moment();
/**
* adding 1 month from the present month and then subtracting 1 day,
* So you would get the last day of this month
*/
dateInst.add(1, 'months').date(1).subtract(1, 'days');
/* printing the last day of this month's date */
console.log(dateInst.format('YYYY MM DD'));
回答by nikhil
your startDate is first-day-of-month, In this case we can use
您的 startDate 是第一天的月份,在这种情况下,我们可以使用
var endDate = moment(startDate).add(1, 'months').subtract(1, 'days');
Hope this helps!!
希望这可以帮助!!
回答by IfThenElse
回答by JSON C11
const year = 2014;
const month = 09;
// months start at index 0 in momentjs, so we subtract 1
const startDate = moment([year, month - 1, 01]).format("YYYY-MM-DD");
// get the number of days for this month
const daysInMonth = moment(startDate).daysInMonth();
// we are adding the days in this month to the start date (minus the first day)
const endDate = moment(startDate).add(daysInMonth - 1, 'days').format("YYYY-MM-DD");
console.log(`start date: ${startDate}`);
console.log(`end date: ${endDate}`);
<script
src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js">
</script>
回答by bharat patel
const dates = getDatesFromDateRange("2014-05-02", "2018-05-12", "YYYY/MM/DD", 1);
console.log(dates);
// you get the whole from-to date ranges as per parameters
var onlyStartDates = dates.map(dateObj => dateObj["to"]);
console.log(onlyStartDates);
// moreover, if you want only from dates then you can grab by "map" function
function getDatesFromDateRange( startDate, endDate, format, counter ) {
startDate = moment(startDate, format);
endDate = moment(endDate, format);
let dates = [];
let fromDate = startDate.clone();
let toDate = fromDate.clone().add(counter, "month").startOf("month").add(-1, "day");
do {
dates.push({
"from": fromDate.format(format),
"to": ( toDate < endDate ) ? toDate.format(format) : endDate.format(format)
});
fromDate = moment(toDate, format).add(1, "day").clone();
toDate = fromDate.clone().add(counter, "month").startOf("month").add(-1, "day");
} while ( fromDate < endDate );
return dates;
}
Please note, .clone() is essential in momentjs else it'll override the value. It seems in your case.
请注意, .clone() 在 momentjs 中是必不可少的,否则它会覆盖该值。看来你的情况。
It's more generic, to get bunch of dates that fall between dates.
它更通用,以获得落在日期之间的一堆日期。
回答by enrique ramos
The following code should work:
以下代码应该可以工作:
$('#reportrange').daterangepicker({
startDate: start,
endDate: end,
ranges: {
'Hoy': [moment(), moment()],
'Ayer': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
'Ultimos 7 dias': [moment().subtract(6, 'days'), moment()],
'Ultimos 30 dias': [moment().subtract(29, 'days'), moment()],
'Mes actual': [moment().startOf('month'), moment().endOf('month')],
'Ultimo mes': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')],
'Enero': [moment().month(0).startOf('month') , moment().month(0).endOf('month')],
'Febrero': [moment().month(1).startOf('month') , moment().month(1).endOf('month')],
'Marzo': [moment().month(2).startOf('month') , moment().month(2).endOf('month')],
'Abril': [moment().month(3).startOf('month') , moment().month(3).endOf('month')],
'Mayo': [moment().month(4).startOf('month') , moment().month(4).endOf('month')],
'Junio': [moment().month(5).startOf('month') , moment().month(5).endOf('month')],
'Julio': [moment().month(6).startOf('month') , moment().month(6).endOf('month')],
'Agosto': [moment().month(7).startOf('month') , moment().month(7).endOf('month')],
'Septiembre': [moment().month(8).startOf('month') , moment().month(8).endOf('month')],
'Octubre': [moment().month(9).startOf('month') , moment().month(9).endOf('month')],
'Noviembre': [moment().month(10).startOf('month') , moment().month(10).endOf('month')],
'Diciembre': [moment().month(11).startOf('month') , moment().month(11).endOf('month')]
}
}, cb);

