如何使用 JavaScript 添加/减去日期? [英] How to add/subtract dates with JavaScript?

查看:24
本文介绍了如何使用 JavaScript 添加/减去日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to let users easily add and subtract dates using JavaScript in order to browse their entries by date.

日期格式为:mm/dd/yyyy".我希望他们能够点击下一步"按钮,如果日期是:06/01/2012"然后点击下一步,它应该变成:06/02/2012".如果他们点击上一个"按钮,那么它应该变成05/31/2012".

The dates are in the format: "mm/dd/yyyy". I want them to be able to click a "Next" button, and if the date is: " 06/01/2012" then on clicking next, it should become: "06/02/2012". If they click the 'prev' button then it should become, "05/31/2012".

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

It needs to keep track of leap years, number of days in the month, etc.

有什么想法吗?

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

P.S using AJAX to get the date from the server isn't an option, its a bit laggy and not the experience for the user that the client wants.

推荐答案

代码:

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 演示

可能会派上用场的额外东西:

Extra stuff that might come handy:

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 日期

这篇关于如何使用 JavaScript 添加/减去日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆