gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 02:21:14 25 4
gpt4 key购买 nike

我的 jQuery 函数接受当前月份。我想根据单击的按钮显示下个月和上个月。

我的问题是,是否有一个 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
});
});

我可以编写一些代码并获取下个月和上个月的数据,但我想知道是否有任何已经定义的函数用于此目的?

已解决

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

最佳答案

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

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。

关于javascript - 如何使用 JavaScript 查找下一个月和上一个月?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18531052/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com