There are lots of sites that describe various ways of dealing with dates in javascript, but all
I wanted was a simple way to read a date that the user had typed in, subtract a day, and then
display this back to the user. I couldn't find anything, so I wrote this one.
<script type="text/javascript">
// Add days to date.
// Params:
// txtDate: date as string
// days: number of days to add, -ve to subtract
// usFormat: true = US format, false = UK format
// Return: new date as string
function DateAdd(txtDate, days, usFormat)
{
var newDateStr;
var dateParts = txtDate.split(/[^0-9]+/);
var year = Number(dateParts[2]);
if (year < 50) // so 0-49 becomes 2000-2049, 50-99 become 1950-1999
year += 2000;
else if (year < 100)
year += 1900;
var unixDate;
if (usFormat)
unixDate = new Date(year.toString(), dateParts[0]-1, dateParts[1]);
else
unixDate = new Date(year.toString(), dateParts[1]-1, dateParts[0]);
unixDate = new Date(unixDate.getTime() + days * 24 * 60 * 60 * 1000);
var newDay = unixDate.getDate().toString();
var newMonth = (unixDate.getMonth()+1).toString();
var newYear = unixDate.getFullYear().toString();
if (usFormat)
newDateStr = (newMonth + "/" + newDay + "/" + newYear);
else
newDateStr = (newDay + "/" + newMonth + "/" + newYear);
return newDateStr;
}
</script>
As an example of using this, I have the following function that is called when the "add" button
is clicked:
<script type="text/javascript">
function DoAddition()
{
var newDate = document.getElementById("StartDateText").value;
var daysToAdd = document.getElementById("DaysToAddText").value;
var usFormat = document.getElementById("USRadio").checked;
newDate = DateAdd(newDate, daysToAdd, usFormat);
document.getElementById("EndDateText").value = newDate;
}
</script>