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

Cli*_*ote 67 javascript jquery date jquery-ui-datepicker

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

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

它需要跟踪闰年,月中的天数等.

有任何想法吗?

使用AJAX从服务器获取日期的PS不是一个选项,它有点滞后而不是客户想要的用户体验.

Tat*_*nit 89

码:

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);
Run Code Online (Sandbox Code Playgroud)

使用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();?
Run Code Online (Sandbox Code Playgroud)

JSFiddle演示

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

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)
Run Code Online (Sandbox Code Playgroud)

良好的链接: MDN日期


dec*_*jau 38

您需要使用getTime()setTime()在javascript Date对象中添加或减去时间.使用setDate()getDate()在达到1,30,31等限制时会导致错误.

使用setTime可以设置以毫秒为单位的偏移量,让Date对象计算其余部分:

var now=new Date();
var yesterdayMs = now.getTime() - 1000*60*60*24*1; // Offset by one day;
now.setTime( yesterdayMs );
Run Code Online (Sandbox Code Playgroud)

  • 这是唯一对我有用的解决方案.当负数用于日期索引时,Date构造函数似乎表现得很奇怪.我发现解决它的唯一方法是直接使用毫秒 (2认同)

Rom*_*ain 14

startdate.setDate(startdate.getDate() - daysToSubtract);


startdate.setDate(startdate.getDate() + daysToAdd);
Run Code Online (Sandbox Code Playgroud)


T.J*_*der 7

JavaScript Date对象可以在这里提供帮助.

第一步是将这些字符串转换为Date实例.这很容易做到:

var str = "06/07/2012"; // E.g., "mm/dd/yyyy";
var dt = new Date(parseInt(str.substring(6), 10),        // Year
                  parseInt(str.substring(0, 2), 10) - 1, // Month (0-11)
                  parseInt(str.substring(3, 5), 10));    // Day
Run Code Online (Sandbox Code Playgroud)

然后你可以做各种有用的计算.JavaScript日期了解闰年等.他们使用理想化的"日"概念,正好是 86,400秒.它们的潜在价值是自大纪元(1970年1月1日午夜)以来的毫秒数; 它可以是The Epoch之前的日期的负数.

有关MDN页面的Date更多信息.

您也可以考虑使用像MomentJS这样的库,这将有助于解析,进行日期数学,格式化......

  • 不要约会与约会的人.只需使用moment.js并保存你的头发. (4认同)