Showing posts with label Add day or month or year using JavaScript. Show all posts
Showing posts with label Add day or month or year using JavaScript. Show all posts

Friday, 7 October 2011

Calculate last date of given month using JavaScript

<html>
<body>
The end date of this month is
<script type="text/javascript">


//Today
var d = new Date();

//var d = new Date(2011, 10, 1);
//alert(d);

//End date of this month
var d = new Date(d.getFullYear(), d.getMonth() + 1, 0);

//alert(d);

var monthNames = [ 'January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December' ];
var endDate = d.getDate() + ' ' + monthNames[d.getMonth()] + ' ' + d.getFullYear();

//alert(endDate);

document.getElementById('prizeDrawEndDate').innerHTML = endDate;

</script>




Click here to try it by copying the script into w3schools try it editor

Monday, 18 July 2011

DateAdd JavaScript function

The following JavaScript function can be used to add the given "duration" to the given "datepart" i.e. "day", "month" or "year". See the example calls and return values and the actual function definition below.


document.write(DateAdd('1/1/2011', 10, 'day')); //returns 11/01/2011
document.write(DateAdd('1/1/2011', 10, 'month')); //returns 31/10/2011
document.write(DateAdd('1/1/2011', 10, 'year')); //returns 31/12/2020
document.write(DateAdd('1/3/2011', 1, 'year')); //returns 29/02/2012

function DateAdd(startDate, duration, datepart)
{
var day = startDate.split("/")[0];
var month = startDate.split("/")[1];
var year = startDate.split("/")[2];

if (typeof (datepart) != "undefined")
{
switch(datepart.toLowerCase())
{
case "year":
year = Number(year) + duration; day = Number(day) - 1;
break;
case "month":
month = Number(month) + duration; day = Number(day) - 1;
break;
case "day":
day = Number(day) + duration;
break;
}
}

var endDate = new Date(year, month - 1, day);
//Month starts from 0. 0 is Jan, 11 is Dec


/*new Date(2012, 0, 0) -- returns 31/Dec/2011
new Date(2012, 1, 0) -- returns 31/Jan/2012
new Date(2012, 1, -1) -- returns 30/Jan/2012
new Date(2012, 13, 1) -- returns 1/Feb/2013
*/


day = endDate.getDate();
month = endDate.getMonth() + 1;
year = endDate.getFullYear();

day = ((day + "").length == 1) ?
("0" + (day + "")) : (day + "");
month = ((month + "").length == 1) ?
("0" + (month + "")) : (month + "");

return ( day + "/" + month + "/" + year );
}



You might be also interested in DateDiff() function which can be used to find the difference in days between 2 given dates.