片刻JS开始和给定月份结束

Fab*_* B. 82 javascript momentjs

我需要计算给定年份= 2014年和月份= 9(2014年9月)的JS日期.

我试过这个:

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());
Run Code Online (Sandbox Code Playgroud)

两个日志都显示:

Tue Sep 30 2014 23:59:59 GMT+0200 (CEST)
Tue Sep 30 2014 23:59:59 GMT+0200 (CEST)
Run Code Online (Sandbox Code Playgroud)

结束日期是正确的但是...为什么开始日期不是?

kly*_*lyd 155

那是因为endOf改变了原始值.

相关报价:

通过将其设置为单位时间的结尾来突变原始时刻.

这是一个示例函数,可以为您提供所需的输出:

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 };
}
Run Code Online (Sandbox Code Playgroud)

参考文献:

  • `moment`是幂等的,所以你也可以使用`endDate = moment(starDate).endOf("month")`**^.^** (3认同)

bak*_*kal 15

当你使用时,.endOf()你正在改变它被调用的对象,所以startDate变成9月30日

您应该使用.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) 
Run Code Online (Sandbox Code Playgroud)


小智 12

您可以直接将其用于月末或开始日期

new moment().startOf('month').format("YYYY-DD-MM");
new moment().endOf("month").format("YYYY-DD-MM");
Run Code Online (Sandbox Code Playgroud)

您可以通过定义新格式来更改格式


小智 5

试试下面的代码:

const moment=require('moment');
console.log("startDate=>",moment().startOf('month').format("YYYY-DD-MM"));
console.log("endDate=>",moment().endOf('month').format("YYYY-DD-MM"));
Run Code Online (Sandbox Code Playgroud)