[javascript] How to add/subtract dates with JavaScript?

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.

This question is related to javascript jquery date jquery-ui-datepicker

The answer is


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


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

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

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.


All these functions for adding date are wrong. You are passing the wrong month to the Date function. More information about the problem : http://www.domdigger.com/blog/?p=9


Something I am using (jquery needed), in my script I need it for the current day, but of course you can edit it accordingly.

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


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!


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

?


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:

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.


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


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

The JavaScript Date object can help here.

The first step is to convert those strings to Date instances. That's easily done:

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 exactly 86,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.

More on the MDN page on Date.

You might also consider using a library like MomentJS, which will help with parsing, doing date math, formatting...


The best date utility I've used is date-fns for a few reasons:

  • Uses the native JavaScript Date format.
  • Immutable; built using pure functions and always returns a new date instance instead of changing the passed one.
  • Modular; import just the functions you need.

Package manager:

"date-fns": "^1.30.1"

Code:

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

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

Simple and awesome.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to date

How do I format {{$timestamp}} as MM/DD/YYYY in Postman? iOS Swift - Get the Current Local Time and Date Timestamp Typescript Date Type? how to convert current date to YYYY-MM-DD format with angular 2 SQL Server date format yyyymmdd Date to milliseconds and back to date in Swift Check if date is a valid one change the date format in laravel view page Moment js get first and last day of current month How can I convert a date into an integer?

Examples related to jquery-ui-datepicker

How to format date with hours, minutes and seconds when using jQuery UI Datepicker? Jquery UI datepicker. Disable array of Dates How to set minDate to current date in jQuery UI Datepicker? Jquery DatePicker Set default date jQuery UI: Datepicker set year range dropdown to 100 years How to add/subtract dates with JavaScript? setting min date in jquery datepicker How do I clear/reset the selected dates on the jQuery UI Datepicker calendar? jQuery Date Picker - disable past dates Getting value from JQUERY datepicker