简体   繁体   中英

JavaScript random generate time in 12-hour format

I tried to random generate time in 12 hours format. Here is my code in Javascript:

randomTime = (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");
  return String(hFormat+hrs+ ":" +mFormat+mins+ " " +amPm);
}

The part where I execute to random generate time:

var myDate = new Date();
var hour = myDate.getUTCHours();
var minute = myDate.getMinutes();

var resultTime = this.randomTime(hour, minute);

I tried to loop 30 times but the minute printed out is only either in 00 or 01 etc. The hour is working fine as I get some values like 9.00AM, 12.00PM etc.

Any ideas?

You shouldn't mix the current date in your answer. This gives results that are not purely random. Use this:

randomTime = () => {
  hrs = Math.round(Math.random() * 24);
  mins = Math.round(Math.random() * 60);    
  var hFormat = (hrs<10 ? "0" : "");
  var mFormat = (mins<10 ? "0" : "");
  var amPm = (hrs<12 ? "AM" : "PM");
  var is12 = (hrs % 12 === 0);

  return amPm === "AM" && !is12 ? String(hFormat+hrs+ ":" +mFormat+mins+ " " +amPm)
                : "AM" && is12  ? String(12 + ":" +mFormat+mins+ " " +amPm)
                : is12 ? String(hFormat+hrs+ ":" +mFormat+mins+ " " +amPm)
                : String(hFormat+(hrs-12)+ ":" +mFormat+mins+ " " +amPm);

}

var resultTime = this.randomTime();
console.log(resultTime);

Note:

It can be a pain to do the exact right formatting, making sure that it displays 12:03AM instead of 00:03AM , for example. This is why, as an exercise, these are great to do by hand with vanilla javascript, however, in production, it is generally wiser to use libraries like moment.js .

You shouldn't pass int he current time. You were limiting the minutes to the current number of minutes past the hour when the function runs. Try this with hours limited to 12 and minutes limited to 60.

 randomTime = () => { hrs = Math.round(Math.random()*12); mins = Math.round(Math.random()*60); var hFormat = (hrs<10 ? "0" : ""); var mFormat = (mins<10 ? "0" : ""); var amPm = (hrs<12 ? "AM" : "PM"); return String(hFormat+hrs+ ":" +mFormat+mins+ " " +amPm); } var resultTime = this.randomTime(); console.log( resultTime ); 

Edit @Sventies beat me to this, go upvote him

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM