Forum Moderators: open

Message Too Old, No Replies

Populate Date

         

aax123

3:59 am on Dec 3, 2005 (gmt 0)

10+ Year Member



I need to figure out how to take into account days of a month not always equalling 30. If the current month has more than or less than 30 days the code below fails. Any ideas how to make this work? What I am wanting to make happen is set current_date = last 30 days.

current_date = new Date();
current_date.setDate(current_date.getDate()-30);
current_month = current_date.getMonth();
current_month = current_month + 1;
current_day = current_date.getDate();
current_year = current_date.getYear();
var fulldate = "" + current_month + "/" + current_day + "/" + current_year;
document.getElementById("beginDate").value = fulldate;

DrDoc

9:56 pm on Dec 4, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



When working with dates it is always best to do so using timestamps. In JavaScript, the getTime function can be used to retreive the timestamp for the date you are working with.

Also, don't forget that you can pass an argument to the Date() function to determine which date to use. The argument passed must be a timestamp. JavaScript uses timestamps in 1000s of a second.

So, in this case, what you could do is simply:

current_date = new Date(new Date().getTime() - (30 * 24 * 60 * 60 * 1000));

Voila! Your

current_date
variable is now set to a date 30 days ago. :)

aax123

3:50 pm on Dec 5, 2005 (gmt 0)

10+ Year Member



Thanks.