如何用JavaScript进行日期加/减?

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

日期的格式是:"mm/dd/yyyy"。我希望他们能够点击一个"下一步"按钮,如果日期是:"06/01/2012",那么点击下一步,它应该变成:"06/02/2012"。如果他们点击'上一页'按钮,那么它应该变成:"2012年5月31日"。

它需要跟踪闰年、每月的天数等。

有什么想法吗?

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

使用Datepicker:

$("#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演示][2]

额外的东西,可能会很方便。

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日期][1]

评论(2)
startdate.setDate(startdate.getDate() - daysToSubtract);

startdate.setDate(startdate.getDate() + daysToAdd);
评论(0)

你可以使用本地的javascript Date对象来跟踪日期。它可以给你当前的日期,让你跟踪日历的具体内容,甚至帮助你管理不同的时区。你可以添加和减去天/小时/秒来改变你正在使用的日期或计算新的日期。

请看一下这个对象参考,以了解更多。

日期

希望这对你有帮助!

评论(0)