我想根据格式“HH:MM AM”制作随机时间的javascript 在我的selenium IDE中。
我尝试了以下代码: javascript {Math.floor(24 * Math.random()+ 00)+“:”+“00 PM”;}
但正如你猜测的那样,它不起作用。 请帮助谢谢。
答案 0 :(得分:1)
Shehryar的答案将为您提供不正确随机的结果,主要是因为它应该乘以12而不是当前的小时数,而不是当前的分钟数。即较少的小时数和分钟数将减少。由于使用圆形而不是地板,也可以获得零小时和60分钟。
HTML和文档对象的使用虽然很好,所以我将复制它:
<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>
答案 1 :(得分:0)
你有没有看过这篇文章: How to format a JavaScript date 这个在Date对象本身上: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date 也许这些链接将为您提供一些解决方案的指导。祝你好运!
编辑:我试过这个jsFiddle来帮助你,请看: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;
}
}