# Random “month & day” with JS ( jQuery )

setInterval(function() {
var days_array = [31,29,31,30,31,30,31,31,30,31,30,31];
var m = randNum(12);
var m_limit = days_array[m-1];
var d = randNum(m_limit);
\$("code").html("day = "+d+"<br>month = "+m);
},1000);
function randNum(limit){var r=Math.floor(Math.random()*limit)+1;return r;}

http://jsfiddle.net/QERu2/

Can any one review this ?

Thanks :D

-

function randNum(limit){var r=Math.floor(Math.random()*limit)+1;return r;}

Can be shortened to:

function randNum(limit){return Math.floor(Math.random()*limit)+1;}

You should also declare your variables outside of the setInterval and then set them inside only if you need to (for example, the days_array never changes so only needs to be decalared once and not every second.

-
thanks so much :D –  l2aelba Aug 24 '12 at 10:41

This is biased towards days in shorter months. If you want every day to be equally likely you should choose a random number from 1 to 365 (366 for leap years) and calculate the day and month from that.

-

I would reduce the visibility of the variables so they won't get overwritten by accident and I'd separate the date creation from displaying them. Like this, for example:

var datePasser = function(callback) {
var randNum = function(max) {
return Math.floor(1 + Math.random() * max);
},
daysInMonth = [31,29,31,30,31,30,31,31,30,31,30,31];
return function() {
var month = randNum(12),
date = randNum(daysInMonth[month - 1]);
callback(month, date);
}
},
printRandomDate = datePasser(function(month, date) {
\$('code').html("day = "+date+"<br>month = "+month);
});
setInterval(printRandomDate, 1000);​
-
function randomMillisecond()
{
return Math.floor(Math.random() * 1000 * 60 * 60 * 24 * 365.25);
}

setInterval(function() {
var date = new Date(randomMillisecond());

\$("code").html("day = " + date.getDate() + "<br>month = " + date.getMonth());
}, 1000);

If you don't need 02/29.

-