I want to make javascript that random time according the format "HH:MM AM" inside my selenium IDE.
I tried the code below: javascript{Math.floor(24*Math.random() + 00) +":" + "00 PM";}
But as you guess, it doesn't work. Please your help thanks.
I want to make javascript that random time according the format "HH:MM AM" inside my selenium IDE.
I tried the code below: javascript{Math.floor(24*Math.random() + 00) +":" + "00 PM";}
But as you guess, it doesn't work. Please your help thanks.
Shehryar's answer will give you results that are not properly random, mostly because it should be multiplying by 12 not the current number of hours, and 60 not the current number of minutes. i.e. Higher numbers of hours and minutes will be less frequent. Also it will be possible to get zero hours and 60 minutes due to the use of round instead of floor.
The HTML and use of document object is good though, so I will copy that:
<div id="timebox"></div>
<script>
function pad(number) {
//Add a leading 0 if the number is less than 10
return ((number<10)?"0":"")+number.toString();
}
function randomTime() {
//Generate random minute in the day (1440 minutes in 24h)
var r = Math.floor(Math.random() * 1440);
//The hour is obtained by dividing by the number of minutes in an hour
//taking the floor of that (drop the decimal fraction)
//take the remainder (modulo) of dividing by 12 (13 -> 1 etc)
//add 1 so that the range is 1-12 rather than 0-11
var HH = pad(1 + (Math.floor(r/60) % 12));
//Take the integer remainder of dividing by 60 (remove the hours)
var MM = pad(r % 60);
//The afternoon starts after 12*60 minutes
var AMPM = (r>=720) ? "PM" : "AM";
return HH + ":" + MM + " " + AMPM;
}
document.getElementById("timebox").innerHTML=randomTime();
</script>
Did you already review this post: How to format a JavaScript date and this on the Date object itself: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date perhaps these links will provide you with some guidance in coming up with a solution. good luck!
EDIT: I've attempted this jsFiddle to help you, please see: http://jsfiddle.net/damf9hf1/3/
HTML:
<div id="timebox"></div>
JS:
var myDate = new Date();
var myHour = myDate.getUTCHours();
var myMinutes = myDate.getMinutes();
myRandom(myHour, myMinutes);
function myRandom(hrs, mins) {
hrs = Math.round(Math.random()*hrs);
mins = Math.round(Math.random()*mins);
var hFormat = (hrs<10 ? "0" : "");
var mFormat = (mins<10 ? "0" : "");
var amPm = (hrs<12 ? "AM" : "PM");
document.getElementById("timebox").innerHTML="Time: " +hFormat+hrs+ ":" +mFormat+mins+ " " +amPm;
}
}