如何使用momentjs创建firstDayOfMonth和lastDayOfMonth函数

Rol*_*ndo 3 javascript momentjs

在javascript中工作我停止了一个非常简单的问题,关于如何使用javascript和momentjs获取月份的第一天和月份的最后一天.我知道在vb应该是一些像:

 Public Function LastDayOfMonth(ByVal current As DateTime) As DateTime
    Dim daysInMonth As Integer = DateTime.DaysInMonth(current.Year, current.Month)
    Return current.FirstDayOfMonth().AddDays(daysInMonth - 1)
End Function

 Public Function FirstDayOfMonth(ByVal current As DateTime) As DateTime
    Return current.AddDays(1 - current.Day)
End Function
Run Code Online (Sandbox Code Playgroud)

我将如何将此代码移动到javascript + momentjs?我认为图书馆没有类似的方法.

谢谢.

Xot*_*750 12

我不知道VB,你的问题不清楚你的输入输出要求.据我所知,这是一个解决方案.它不是使用moment.js而是使用POJS.如果您愿意,可以轻松将其转换为使用时刻(不知道为什么会这样).

使用Javascript

function firstDayOfMonth() {
    var d = new Date(Date.apply(null, arguments));

    d.setDate(1);
    return d.toISOString();
}

function lastDayOfMonth() {
    var d = new Date(Date.apply(null, arguments));

    d.setMonth(d.getMonth() + 1);
    d.setDate(0);
    return d.toISOString();
}

var now = Date.now();

console.log(firstDayOfMonth(now));
console.log(lastDayOfMonth(now));
Run Code Online (Sandbox Code Playgroud)

产量

2013-06-01T21:22:48.000Z 
2013-06-30T21:22:48.000Z 
Run Code Online (Sandbox Code Playgroud)

请参阅格式的日期

jsfiddle

利用时刻,你可以做到这一点.

使用Javascript

console.log(moment().startOf('month').utc().toString());
console.log(moment().endOf("month").utc().toString());
Run Code Online (Sandbox Code Playgroud)

产量

2013-06-01T00:00:00+02:00
2013-06-30T23:59:59+02:00
Run Code Online (Sandbox Code Playgroud)

查看格式的时刻

jsfiddle