Forum Moderators: open

Message Too Old, No Replies

easy -I think - question about date()

returning +1 day

         

spud_nic

4:34 pm on Feb 18, 2006 (gmt 0)

10+ Year Member



Hi

I'm using a javascript calendar from a tutorial website, which is great and works really well.

I've successfully altered it to do exactly what I want, but I've become stuck.

It has this code:


cal18.addDisabledDates(null,formatDate(now,"yyyy-MM-dd"));

which calls a function:


function formatDate(date,format){format=format+"";var result="";var i_format=0;var c="";var token="";var y=date.getYear()+"";var M=date.getMonth()+1;var d=date.getDate(); ---- and it goes on and on

I want it to return today - 1, -0, or + 1, i.e. yesterday today, or tomorrow. If I change the last part of the function to d=date.getDate()+1; it works!
But if I try and pass a parameter, it doesn't! and NaN is returned.
I've tried this:

cal18.addDisabledDates(null,formatDate(now,"yyyy-MM-dd"),1);
...
function formatDate(date,format,days)
...
d=date.getDate()+parseInt(days);

...where the passed "1" is the number of days to increase by.

Can anyone advise me further? Will I be able to call a javascript function to change this dynamically too?

Thanks for reading, and please help if you can!

DrDoc

6:18 pm on Feb 18, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Personally, what I would do is add or subtract 86400000 (number of milliseconds in a day, which is what JS timestamps are based on) to the function which assigns the date variable itself. That way you can ensure to get proper month/year results as well.

<script type="text/javascript">
var date = new Date();
document.write(date + "<br>");
var date = new Date(new Date().getTime() + 86400000);
document.write(date);
</script>

mrhoo

7:43 am on Feb 22, 2006 (gmt 0)

10+ Year Member



If you do this a lot you can extend the Date prototype:
n is the number of days
boo is a boolean- true returns UTC time

Date.prototype.addDay= function(n,boo){
if(!n) n= 1;
n*=(86400000);
var x= (this.getTime()+n);
x= new Date(x);
if(boo)x= x.toUTCString();
return x;
}

d is a second date
n is a number of days-if n is 7 it returns weeks

Date.prototype.daysFrom= function(d,n){
if(!d) d= new Date();
if(!n) n=1;
var x= this.getTime()- d.getTime();
var y= n*(86400000);
return Math.round(x/y);
};

DrDoc

7:59 am on Feb 22, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Welcome to WebmasterWorld! [WebmasterWorld.com]

And thanks for that valuable tip :)