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

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

日期的格式是: “ mm/dd/yyyy”。我希望他们能够点击“下一步”按钮,如果日期是: “06/01/2012”,然后点击下一步,它应该是: “06/02/2012”。如果他们点击‘ prev’按钮,那么应该是“05/31/2012”。

它需要记录闰年,一个月中的天数等等。

有什么想法吗?

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

258170 次浏览

您可以使用原生的 javascript Date 对象来跟踪日期。它会给你当前的日期,让你跟踪日历特定的东西,甚至帮助你管理不同的时区。您可以添加和减去天/小时/秒,以更改正在处理的日期或计算新的日期。

看一下这个对象引用,了解更多:

日期

希望能帮上忙!

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




startdate.setDate(startdate.getDate() + daysToAdd);

密码:

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

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

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)

好链接: < a href = “ http://jsfiddle.net/2YkeK/”rel = “ norefrer”> MDN Date

也许这个能帮上忙

    <script type="text/javascript" language="javascript">
function AddDays(toAdd) {
if (!toAdd || toAdd == '' || isNaN(toAdd)) return;
var d = new Date();
d.setDate(d.getDate() + parseInt(toAdd));


document.getElementById("result").innerHTML = d.getDate() + "/" + d.getMonth() + "/" + d.getFullYear();
}


function SubtractDays(toAdd) {
if (!toAdd || toAdd == '' || isNaN(toAdd)) return;
var d = new Date();
d.setDate(d.getDate() - parseInt(toAdd));


document.getElementById("result").innerHTML = d.getDate() + "/" + d.getMonth() + "/" + d.getFullYear();
}
</script>
---------------------- UI ---------------
<div id="result">
</div>
<input type="text" value="0" onkeyup="AddDays(this.value);" />
<input type="text" value="0" onkeyup="SubtractDays(this.value);" />

JavaScriptDate对象可以在这里提供帮助。

第一步是将这些字符串转换为 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

然后你可以做各种有用的计算。JavaScript 日期能够理解闰年等等。他们使用一个理想化的概念“一天”,这是 没错86,400秒长。它们的基本值是自“新纪元”(1970年1月1日午夜)以来的毫秒数; 对于“新纪元”之前的日期,它可以是负数。

更多关于 Date上的 MDN 页面的资料。

您也可以考虑使用类似 等一下的库,这将有助于解析、进行日期数学、格式化... ..。

在 javascript 中处理日期总是有点麻烦。我最后总是用图书馆。Moment.js 和 XDate 都很棒:

Http://momentjs.com/

Http://arshaw.com/xdate/

提琴:

Http://jsfiddle.net/39fwa/

var $output = $('#output'),
tomorrow = moment().add('days', 1);


$('<pre />').appendTo($output).text(tomorrow);


tomorrow = new XDate().addDays(-1);


$('<pre />').appendTo($output).text(tomorrow);

//In order to get yesterday's date in mm/dd/yyyy.




function gimmeYesterday(toAdd) {
if (!toAdd || toAdd == '' || isNaN(toAdd)) return;
var d = new Date();
d.setDate(d.getDate() - parseInt(toAdd));
var yesterDAY = (d.getMonth() +1) + "/" + d.getDate() + "/" + d.getFullYear();
$("#endDate").html(yesterDAY);
}
$(document).ready(function() {
gimmeYesterday(1);
});

你可以试试这里: http://jsfiddle.net/ZQAHE/

所有这些添加日期的函数都是错误的。将错误的月份传递给 Date 函数。更多有关问题的信息: Http://www.domdigger.com/blog/?p=9

You need to use getTime() and setTime() to add or substract the time in a javascript Date object. Using setDate() and getDate() will lead to errors when reaching the limits of the months 1, 30, 31, etc..

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

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

我喜欢的方法是,如果你有一个日期对象,你可以从中减去另一个日期对象来得到差值。日期对象基于某个日期的毫秒。

var date1 = new Date(2015, 02, 18); // "18/03/2015", month is 0-index
var date2 = new Date(2015, 02, 20); // "20/03/2015"


var msDiff = date2 - date1; // 172800000, this is time in milliseconds
var daysDiff = msDiff / 1000 / 60 / 60 / 24; // 2 days

So this is how you subtract dates. Now if you want to add them? date1 + date2 gives an error.. But if I want to get the time in ms I can use:

var dateMs = date1 - 0;
// say I want to add 5 days I can use
var days = 5;
var msToAdd = days * 24 * 60 * 60 * 1000;
var newDate = new Date(dateMs + msToAdd);

通过减去0,可以将日期对象转换为毫秒格式。

我正在使用的东西(需要 jquery) ,在我的脚本中,我需要它为当前日期,但是当然你可以相应地编辑它。

HTML:

<label>Date:</label><input name="date" id="dateChange" type="date"/>
<input id="SubtractDay" type="button" value="-" />
<input id="AddDay" type="button" value="+" />

JavaScript:

    var counter = 0;


$("#SubtractDay").click(function() {
counter--;
var today = new Date();
today.setDate(today.getDate() + counter);
var formattedDate = new Date(today);
var d = ("0" + formattedDate.getDate()).slice(-2);
var m = ("0" + (formattedDate.getMonth() + 1)).slice(-2);
var y = formattedDate.getFullYear();
$("#dateChange").val(d + "/" + m + "/" + y);
});
$("#AddDay").click(function() {
counter++;
var today = new Date();
today.setDate(today.getDate() + counter);
var formattedDate = new Date(today);
var d = ("0" + formattedDate.getDate()).slice(-2);
var m = ("0" + (formattedDate.getMonth() + 1)).slice(-2);
var y = formattedDate.getFullYear();
$("#dateChange").val(d + "/" + m + "/" + y);
});

Jsfiddle

var date = new Date('your date string here'); // e.g. '2017-11-21'


var newdate = new Date(date.getTime() + 24*60*60*1000 * days) // days is the number of days you want to shift the date by

这是唯一的解决方案,可靠的工作时,加/减跨月和年。在花费了太多时间在 getDate 和 setDate 方法上之后,我意识到了这一点。

Decasteljau (在这个线程中)已经回答了这个问题,但是只是想强调这个方法的实用性,因为90% 的回答都推荐使用 getDate 和 setDate 方法。

我使用的最佳 date 工具是 约会,原因如下:

  • 使用本机 JavaScriptDate格式。
  • 不可变的; 使用纯函数构建,并且总是返回一个新的日期实例,而不是更改传递的日期实例。
  • 模块化; 只导入所需的函数。

包裹经理:

"date-fns": "^1.30.1"

密码:

import { addDays, subDays } from 'date-fns'

let today = new Date()
let yesterday = subDays(today, 1)
let tomorrow = addDays(today, 1)

简单又棒。

如果你使用 moment.js

例子:

moment(currentDate).add('days',3) // adds 3 days
moment(currentDate).subtract('days',3) // 3 days subtract

或者

moment(currentDate).add('hours',3) // adds 3 hour
moment(currentDate).subtract('hours',3) // 3 hour subtract