how to add days to date in javascript

Posted by Klbaiju under JavaScript on 8/25/2010 | Points: 10 | Views : 35974 | Status : [Member] | Replies : 2
Hi following is the javascript code which i used for adding days to date

my date is 25/08/2010 and i want to add 8 days to this date the answer should be 03/09/2010. how it is possible. i tried following code but showing error.



Regards

K L BAIJU



<script type="text/javascript" language="javascript">

function check()
{
var myDate = new Date();
myDate.setDate(myDate.getDate()+8);
var vFormat="MM/dd/yyyy";
var vDay = addZero(myDate.getDate());
var vMonth = addZero(myDate.getMonth()+1);
var vYearLong = addZero(myDate.getFullYear());
var vYearShort = addZero(myDate.getFullYear().toString().substring(3,4));
var vYear = (vFormat.indexOf("yyyy")>-1?vYearLong:vYearShort)
var vHour = addZero(myDate.getHours());
var vMinute = addZero(myDate.getMinutes());
var vSecond = addZero(myDate.getSeconds());
var myDateString = vFormat.replace(/dd/g, vDay).replace(/MM/g, vMonth).replace(/y{1,4}/g, vYear)
myDateString = myDateString.replace(/hh/g, vHour).replace(/mm/g, vMinute).replace(/ss/g, vSecond)
alert(myDateString);
}

function addZero(vNumber){
return ((vNumber < 10) ? "0" : "") + vNumber
}

</script>




Responses

Posted by: SheoNarayan on: 8/25/2010 [Administrator] HonoraryPlatinum | Points: 25

Up
0
Down
Hi Klbaiju,

You do not need to write this much of bigger function, just use following code snippet

<script language="javascript" type="text/javascript">

// function to add number of days (accepts number of days to add)
function AddDays(days) {
var thisDate = new Date();
thisDate.setDate(thisDate.getDate() + days);
return thisDate;
}

// call your function like this
alert(AddDays(8));
</script>


For date related functions in JavaScript, visit http://www.quackit.com/javascript/javascript_date_and_time_functions.cfm

Thanks

Regards,
Sheo Narayan
http://www.dotnetfunda.com

Klbaiju, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Klbaiju on: 8/26/2010 [Member] Starter | Points: 25

Up
0
Down
Hi Mr Sheo narayan,

your code is working fine.the problem is it is taking system date.and display in MMM-dd-yyyy format.
eg: sat sep 04 2010 11:34:35 GMT +0530(india standard time).
i don't need this format.
my reqiurement is date is coming from a textbox.
eg:- 26/07/2010

days from this statement

var day1=document.getElementById('<%=Hiddenpackage.ClientID %>').value;

i want to use your code like this

alert(addDays(day1)

eg:- if the date is 28/08/2010 and day1=5
the added date should be 02/09/2010

what i have to change in your code.

it is very urgent for me
Regards
K L BAIJU

Klbaiju, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response