如何使用时刻js创建第一个Day of Month和lastDayOfMonth函数

时间:2013-06-17 19:37:07

标签: 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

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

谢谢。

1 个答案:

答案 0 :(得分: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));

输出

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

请参阅Date了解格式

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

请参阅moments了解格式

jsfiddle