如何使用 JavaScript 查找下个月和上个月?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18531052/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 12:17:58  来源:igfitidea点击:

How to find the next and previous months with JavaScript?

javascriptjquerydatemonthcalendar

提问by user2354302

My jQuery function takes in the current month. I would like to display the next and previous months depending on the buttons clicked.

我的 jQuery 函数接受current month. 我想根据单击的按钮显示下个月和上个月。

My question is, is there a defaultDate()function I can call to know the next and previous months of a current month ?

我的问题是,有没有defaultDate()我可以调用的函数来了解当前月份的下个月和上个月?

$(document).ready(function () {
    var current_date = $('#cal-current-month').html();
    //current_date will have September 2013
    $('#previous-month').onclick(function(){
        // Do something to get the previous month
    });
    $('#next-month').onclick(function(){
        // Do something to get the previous month
    });
});

I can write some code and get the next and previous months, but I was wondering if there is any already defined functionsfor this purpose?

我可以编写一些代码并获得下个月和上个月的数据,但我想知道是否已经defined functions有用于此目的的代码?

SOLVED

解决了

var current_date = $('.now').html();
var now = new Date(current_date);

var months = new Array( "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");

$('#previous-month').click(function(){
    var past = now.setMonth(now.getMonth() -1);
    $('.now').html(months[now.getMonth()]+' '+now.getFullYear());
});

$('#next-month').click(function(){
    var future = now.setMonth(now.getMonth() +1);
    $('.now').html(months[now.getMonth()]+' '+now.getFullYear());
});

回答by Daniel Bank

If you just want to get the first day of the next month, you could do something like:

如果您只想获得下个月的第一天,您可以执行以下操作:

var now = new Date();
var future = now.setMonth(now.getMonth() + 1, 1);
var past = now.setMonth(now.getMonth() - 1, 1);

This will prevent the "next" month from skipping a month (e.g. adding a month to January 31, 2014 will result in March 3rd, 2014 if you omit the second parameter).

这将防止“下一个”月份跳过一个月(例如,如果省略第二个参数,将一个月添加到 2014 年 1 月 31 日将导致 2014 年 3 月 3 日)。

As an aside, using date.js* you could do the following:

顺便说一句,使用date.js* 您可以执行以下操作:

var today = Date.today();
var past = Date.today().add(-1).months();
var future = Date.today().add(1).months();

In this example I am using today's date, but it works for any date.

在这个例子中,我使用今天的日期,但它适用于任何日期。

*date.js has been abandoned. If you decide to use a library, you should probably use moment.js as RGraham suggests.

*date.js 已被放弃。如果你决定使用一个库,你应该像 RGraham 建议的那样使用 moment.js。