我的应用程序需要在 moment js 中具有以下功能。
var nDay = moment(2007, 0, 28).next('date'); //--> 2007-0-29T00:00:00.00
var pDay = moment(2007, 0, 28).previous('date'); //--> 2007-0-27T00:00:00.00
同样:
.next('week'), .next('month')
并获取特定日期。
我知道 momentjs 有操作方法,但使用它们很痛苦,因为它会改变原始方法。即使使用 .clone()
,这也不容易。
那么各位,如何在 moment 或 js 中实现这个 next()
和 previous()
方法?
或者,查找特定日期之后的最简单方法是什么?
最佳答案
正如您在问题中所说,您可以使用矩操作函数,如 add
和 subtract
以及clone
以避免原始对象发生突变。
要添加自定义函数,请使用 moment.fn
.
矩操作函数接受 'months'
、'weeks'
、'days'
等作为参数,而您似乎想要使用 'month'
、'week'
、'date'
,因此您需要将输入字符串转换为等效时刻。
这里有一个工作示例:
moment.fn.next = function(unit){
// Convert input to strings used by moment
unit = unit === 'date' ? 'days' : unit;
if( unit === 'month' || unit === 'week'){
unit += 's';
}
return this.clone().add(1, unit);
}
moment.fn.previous = function(unit){
// Convert input to strings used by moment
unit = unit === 'date' ? 'days' : unit;
if( unit === 'month' || unit === 'week'){
unit += 's';
}
return this.clone().subtract(1, unit);
}
var nDay = moment([2007, 0, 28]).next('date');
var pDay = moment([2007, 0, 28]).previous('date');
var nMonth = moment([2007, 0, 28]).next('month');
console.log(nDay.format());
console.log(pDay.format());
console.log(nMonth.format());
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.14.1/moment.min.js"></script>
关于javascript - 在 moment.js 中查找日期、另一个日期的 X 持续时间的最简单方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39184845/