【问题标题】:How to find the next and previous months with JavaScript?如何使用 JavaScript 查找下个月和上个月?
【发布时间】:2013-08-30 10:47:58
【问题描述】:

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

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

$(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
    });
});

我可以编写一些代码并获取下个月和前几个月的信息,但我想知道是否已经有 defined functions 用于此目的?

已解决

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());
});

【问题讨论】:

    标签: javascript jquery date monthcalendar


    【解决方案1】:

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

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

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

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

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

    在此示例中,我使用的是今天的日期,但它适用于任何日期。

    *date.js 已被放弃。如果您决定使用库,您可能应该按照 RGraham 的建议使用 moment.js。

    【讨论】:

    • 这有帮助。非常感谢:)
    • 我设置了 - new Date().setMonth(new Date().getMonth() + 2, 1) 并得到了 - 1404212502044。这个数字是多少?如何提取和显示月份?
    • @arjun const MONTH_NAMES = [“一月”、“二月”、“三月”、“四月”、“五月”、“六月”、“七月”、“八月”、“九月”、“十月”、“十一月”、“十二月”]; MONTH_NAMES[new Date(future).getMonth()]
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-05
    • 1970-01-01
    相关资源
    最近更新 更多