我正在尝试获取本月的开始和结束时间,但对于三月,它给了我开始日期 2020-02-29T00:00:00.000Z
使用momentjs
var firstDay = new moment().startOf('month').utcOffset(0);
firstDay.set({hour:0,minute:0,second:0,millisecond:0});
var lastDay = new moment().endOf('month').utcOffset(0);
lastDay.set({hour:23,minute:59,second:59,millisecond:0})
使用Date()
var date = new Date(),
y = date.getFullYear(),
m = date.getMonth();
var firstDay = new Date(y, m, 1);
var lastDay = new Date(y, m + 1, 1);
如何解决这个问题?
答案 0 :(得分:3)
尝试startOf / endOf,后跟utcOffset()
注意::开始时间-设置为本月的第一天,上午12:00
var firstDay = new moment('2020-02-29T00:00:00.000Z').utcOffset(0).startOf('month');
console.log(firstDay.format())
var lastDay = new moment('2020-02-29T00:00:00.000Z').utcOffset(0).endOf('month');
console.log(lastDay.format())
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
答案 1 :(得分:0)
对于行军,应该使用utcOffset(0)
这样,然后调用函数startof()
:
var startDay = new moment().utcOffset(0).startOf('month').format();
var endDay = new moment().utcOffset(0).endOf('month').format();
console.log(startDay);
console.log(endDay);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>