How to add/subtract dates with JavaScript?

2019-01-03 05:35发布

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

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.

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.

13条回答
一夜七次
2楼-- · 2019-01-03 06:06

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:

http://momentjs.com/

http://arshaw.com/xdate/

Fiddle:

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);

查看更多
劫难
3楼-- · 2019-01-03 06:11
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.

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.

查看更多
The star\"
4楼-- · 2019-01-03 06:13

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);" />
查看更多
We Are One
5楼-- · 2019-01-03 06:16

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..

Using setTime allows you to set an offset in milliseconds, and let the Date object figure the rest:

var now=new Date();
var yesterdayMs = now.getTime() - 1000*60*60*24*1; // Offset by one day;
now.setTime( yesterdayMs );
查看更多
淡お忘
6楼-- · 2019-01-03 06:17
//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/

查看更多
戒情不戒烟
7楼-- · 2019-01-03 06:19

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.

take a look at this object reference to learn more:

Date

Hope that helps!

查看更多
登录 后发表回答