如何使用 JavaScript 添加/减去日期?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10931288/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add/subtract dates with JavaScript?
提问by Click Upvote
I want to let users easily add and subtract dates using JavaScript in order to browse their entries by date.
我想让用户使用 JavaScript 轻松添加和减去日期,以便按日期浏览他们的条目。
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".
日期格式为:“mm/dd/yyyy”。我希望他们能够点击“下一步”按钮,如果日期是:“06/01/2012”然后点击下一步,它应该变成:“06/02/2012”。如果他们点击“prev”按钮,那么它应该变成“05/31/2012”。
It needs to keep track of leap years, number of days in the month, etc.
它需要跟踪闰年、一个月中的天数等。
Any ideas?
有任何想法吗?
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.
PS 使用 AJAX 从服务器获取日期不是一种选择,它有点滞后,而不是客户端想要的用户体验。
回答by Tats_innit
Code:
代码:
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);
Using 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();?
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)
Good link:MDN Date
好链接:MDN 日期
回答by decasteljau
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..
您需要使用getTime()
和setTime()
在 javascript Date 对象中添加或减去时间。使用setDate()
和getDate()
会在达到 1、30、31 等月份的限制时导致错误。
Using setTime allows you to set an offset in milliseconds, and let the Date object figure the rest:
使用 setTime 允许您以毫秒为单位设置偏移量,并让 Date 对象计算其余部分:
var now=new Date();
var yesterdayMs = now.getTime() - 1000*60*60*24*1; // Offset by one day;
now.setTime( yesterdayMs );
回答by Romil Kumar Jain
startdate.setDate(startdate.getDate() - daysToSubtract);
startdate.setDate(startdate.getDate() + daysToAdd);
回答by T.J. Crowder
The JavaScript Date
object can help here.
JavaScriptDate
对象可以在这里提供帮助。
The first step is to convert those strings to Date
instances. That's easily done:
第一步是将这些字符串转换为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
Then you can do all sorts of useful calculations. JavaScript dates understand leap years and such. They use an idealized concept of "day" which is exactly86,400 seconds long. Their underlying value is the number of milliseconds since The Epoch (midnight, Jan 1st, 1970); it can be a negative number for dates prior to The Epoch.
然后你可以做各种有用的计算。JavaScript 日期理解闰年等。他们使用理想化的“日”概念,即恰好86,400 秒长。它们的基本值是自大纪元(1970 年 1 月 1 日午夜)以来的毫秒数;对于 The Epoch 之前的日期,它可以是负数。
More on the MDN page on Date
.
更多关于MDN 页面的信息Date
。
You might also consider using a library like MomentJS, which will help with parsing, doing date math, formatting...
您也可以考虑使用像MomentJS这样的库,它有助于解析、计算日期、格式化……
回答by thetallone
//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);
});
you can try here: http://jsfiddle.net/ZQAHE/
你可以在这里试试:http: //jsfiddle.net/ZQAHE/
回答by benvds
Working with dates in javascript is always a bit of a hassle. I always end up using a library. Moment.js and XDate are both great:
在 javascript 中处理日期总是有点麻烦。我总是最终使用图书馆。Moment.js 和 XDate 都很棒:
Fiddle:
小提琴:
var $output = $('#output'),
tomorrow = moment().add('days', 1);
$('<pre />').appendTo($output).text(tomorrow);
tomorrow = new XDate().addDays(-1);
$('<pre />').appendTo($output).text(tomorrow);
?
?
回答by yogi
May be this could help
可能这会有所帮助
<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);" />
回答by Jake Rowsell
The way I like, is if you have a date object you can subtract another date object from it to get the difference. Date objects are based on milliseconds from a certain date.
我喜欢的方式是,如果您有一个日期对象,您可以从中减去另一个日期对象以获得差异。日期对象基于某个日期的毫秒数。
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:
所以这就是你如何减去日期。现在,如果您想添加它们?date1 + date2 给出错误.. 但是如果我想以毫秒为单位获取时间,我可以使用:
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);
By subtracting 0 you turn the date object into the milliseconds format.
通过减去 0,您将日期对象转换为毫秒格式。
回答by Suparna Gharpure
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
This is the only solution that works reliably when adding/subtracting across months and years. Realized this after spending way too much time mucking around with the getDate and setDate methods, trying to adjust for month/year shifts.
这是在跨月和跨年加/减时唯一可靠的解决方案。在花了太多时间处理 getDate 和 setDate 方法,试图调整月/年变化后意识到这一点。
decasteljau (in this thread) has already answered this but just want to emphasize the utility of this method because 90% of the answers out there recommend the getDate and setDate approach.
decasteljau(在此线程中)已经回答了这个问题,但只是想强调这种方法的实用性,因为 90% 的答案都推荐 getDate 和 setDate 方法。
回答by Logard
You can use the native javascript Date object to keep track of dates. It will give you the current date, let you keep track of calendar specific stuff and even help you manage different timezones. You can add and substract days/hours/seconds to change the date you are working with or to calculate new dates.
您可以使用本机 javascript Date 对象来跟踪日期。它将为您提供当前日期,让您跟踪日历特定的内容,甚至帮助您管理不同的时区。您可以添加和减去天/小时/秒来更改您正在使用的日期或计算新日期。
take a look at this object reference to learn more:
查看此对象参考以了解更多信息:
Hope that helps!
希望有帮助!