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

how to create firstDayOfMonth and lastDayOfMonth functions using momentjs

本文关键字:lastDayOfMonth 函数 firstDayOfMonth 创建 何使用 momentjs      更新时间:2023-09-26

在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

我该如何将这段代码移动到javascript + momentjs?我想图书馆没有类似的方法。

谢谢。

我不懂VB,你的问题不清楚你的输入输出要求。据我所知,这是一个解决办法。它不是使用moments.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));

输出
2013-06-01T21:22:48.000Z 
2013-06-30T21:22:48.000Z 

格式请参见日期

在jsfiddle

使用力矩,你可以这样做。

Javascript

console.log(moment().startOf('month').utc().toString());
console.log(moment().endOf("month").utc().toString());

输出
2013-06-01T00:00:00+02:00
2013-06-30T23:59:59+02:00

格式见矩

在jsfiddle