片刻JS开始和给定月份结束 [英] Moment JS start and end of given month
本文介绍了片刻JS开始和给定月份结束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要计算给定年份= 2014年和月份= 9(2014年9月)的JS日期。
I need to calculate a JS date given year=2014 and month=9 (September 2014).
我试过这个:
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());
两个日志显示:
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?
推荐答案
那是因为 endOf
改变原始值。
That's because endOf
mutates the original value.
相关报价:
通过将原始时刻设置为单位时间的结尾来突变原始时刻。
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 };
}
参考文献:
endOf()
clone()
Date from object
这篇关于片刻JS开始和给定月份结束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文