javascript - 如何使用 JavaScript 添加/减去日期?

标签 javascript jquery date jquery-ui-datepicker

我想让用户使用 JavaScript 轻松地添加和减去日期,以便按日期浏览他们的条目。

日期的格式为:“mm/dd/yyyy”。我希望他们能够单击“下一步”按钮,如果日期是:“06/01/2012”,那么在单击下一步时,它应该变为:“06/02/2012”。如果他们点击“上一个”按钮,那么它应该变成“05/31/2012”。

它需要跟踪闰年、一个月中的天数等。

有什么想法吗?

P.S 使用 AJAX 从服务器获取日期不是一种选择,它有点滞后并且不是客户想要的用户体验。

最佳答案

代码:

var date = new Date('2011', '01', '02');
alert('the original date is ' + date);
var newdate = new Date(date);

newdate.setDate(newdate.getDate() - 7); // minus the date

var nd = new Date(newdate);
alert('the new date is ' + nd);

使用日期选择器:

$("#in").datepicker({
    minDate: 0,
    onSelect: function(dateText, inst) {
       var actualDate = new Date(dateText);
       var newDate = new Date(actualDate.getFullYear(), actualDate.getMonth(), actualDate.getDate()+1);
        $('#out').datepicker('option', 'minDate', newDate );
    }
});

$("#out").datepicker();​

JSFiddle Demo

可能会派上用场的额外内容:

getDate()   Returns the day of the month (from 1-31)
getDay()    Returns the day of the week (from 0-6)
getFullYear()   Returns the year (four digits)
getHours()  Returns the hour (from 0-23)
getMilliseconds()   Returns the milliseconds (from 0-999)
getMinutes()    Returns the minutes (from 0-59)
getMonth()  Returns the month (from 0-11)
getSeconds()    Returns the seconds (from 0-59)

好的链接: MDN Date

关于javascript - 如何使用 JavaScript 添加/减去日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10931288/

相关文章:

javascript - 在同一迭代中过滤和映射

javascript - 无法以编程方式单击 Greasemonkey 脚本中的 <a> 标记

javascript - 复选框值真/假

javascript - Highcharts X 轴新值

javascript - Pubnub - 取消订阅特定 channel 的所有活跃用户

处理时区转换的 JavaScript 库

javascript - 未捕获的 TypeError : $(. ..).modal 不是函数 jquery

javascript - 如何在 HTML 中动态创建列表?

mysql - Django mysql 数据库不接受日期格式

javascript - 从 Moment.js 的特定日期开始的几天/几周前