Reputation: 267127
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.
Upvotes: 73
Views: 267615
Reputation: 923
if you use the moment.js
examples:
moment(currentDate).add('days',3) // adds 3 days
moment(currentDate).subtract('days',3) // 3 days subtract
or
moment(currentDate).add('hours',3) // adds 3 hour
moment(currentDate).subtract('hours',3) // 3 hour subtract
Upvotes: 0
Reputation: 9160
The best date utility I've used is date-fns for a few reasons:
Date
format.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.
Upvotes: 1
Reputation: 34107
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
Upvotes: 100
Reputation: 409
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.
Upvotes: 2
Reputation:
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);
});
Upvotes: 0
Reputation: 466
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.
Upvotes: 2
Reputation: 86
//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/
Upvotes: 4
Reputation: 8033
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 );
Upvotes: 42
Reputation: 51
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
Upvotes: 1
Reputation: 3726
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:
Fiddle:
var $output = $('#output'),
tomorrow = moment().add('days', 1);
$('<pre />').appendTo($output).text(tomorrow);
tomorrow = new XDate().addDays(-1);
$('<pre />').appendTo($output).text(tomorrow);
Upvotes: 3
Reputation: 1074666
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...
Upvotes: 8
Reputation: 19621
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);" />
Upvotes: 3
Reputation: 20755
startdate.setDate(startdate.getDate() - daysToSubtract);
startdate.setDate(startdate.getDate() + daysToAdd);
Upvotes: 15
Reputation: 1513
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:
Hope that helps!
Upvotes: 1