Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
274 views
in Technique[技术] by (71.8m points)

javascript - 在JavaScript中增加日期(Incrementing a date in JavaScript)

I need to increment a date value by one day in JavaScript.(我需要在JavaScript中将日期值增加一天。)

For example, I have a date value 2010-09-11 and I need to store the date of the next day in a JavaScript variable.(例如,我的日期值为2010-09-11,我需要将第二天的日期存储在JavaScript变量中。) How can I increment a date by a day?(如何将日期增加一天?)   ask by Santanu translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Three options for you:(为您提供三种选择:)

1. Using just JavaScript's Date object (no libraries):(1.仅使用JavaScript的Date对象(不使用库):) My previous answer for #1 was wrong (it added 24 hours, failing to account for transitions to and from daylight saving time; Clever Human pointed out that it would fail with November 7, 2010 in the Eastern timezone).(我先前对#1的回答是错误的(它增加了24小时,未能考虑到夏时制的转换; Clever Human指出,东部时区到2010年11月7日将失败)。) Instead, Jigar's answer is the correct way to do this without a library:(相反, Jigar的答案是在没有库的情况下执行此操作的正确方法:) var tomorrow = new Date(); tomorrow.setDate(tomorrow.getDate() + 1); This works even for the last day of a month (or year), because the JavaScript date object is smart about rollover:(这甚至在一个月(或一年)的最后一天都可以使用,因为JavaScript日期对象对过渡很聪明:) var lastDayOf2015 = new Date(2015, 11, 31); snippet.log("Last day of 2015: " + lastDayOf2015.toISOString()); var nextDay = new Date(+lastDayOf2015); var dateValue = nextDay.getDate() + 1; snippet.log("Setting the 'date' part to " + dateValue); nextDay.setDate(dateValue); snippet.log("Resulting date: " + nextDay.toISOString()); <!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 --> <script src="//tjcrowder.github.io/simple-snippets-console/snippet.js"></script> (This answer is currently accepted, so I can't delete it. Before it was accepted I suggested to the OP they accept Jigar's, but perhaps they accepted this one for items #2 or #3 on the list.)((此答案目前已被接受,因此我无法删除。在被接受之前,我向OP建议他们接受Jigar的答案,但也许他们接受列表中第2或#3项的答案。)) 2. Using MomentJS :(2.使用MomentJS :) var today = moment(); var tomorrow = moment(today).add(1, 'days'); (Beware that add modifies the instance you call it on, rather than returning a new instance, so today.add(1, 'days') would modify today . That's why we start with a cloning op on var tomorrow = ... .)((请注意, add会修改您调用的实例,而不是返回新实例,因此today.add(1, 'days')会在today修改。这就是为什么我们从var tomorrow = ...上克隆op的原因。 )) 3. Using DateJS , but it hasn't been updated in a long time:(3.使用DateJS ,但是很长一段时间没有更新:) var today = new Date(); // Or Date.today() var tomorrow = today.add(1).day();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...