JavaScript random generate time in 12-hour format -


i tried random generate time in 12 hours format. here 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 execute random generate time:

var mydate = new date(); var hour = mydate.getutchours(); var minute = mydate.getminutes();  var resulttime = this.randomtime(hour, minute); 

i tried loop 30 times minute printed out either in 00 or 01 etc. hour working fine values 9.00am, 12.00pm etc.

any ideas?

you shouldn't mix current date in answer. gives results 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 pain exact right formatting, making sure displays 12:03am instead of 00:03am, example. why, exercise, these great hand vanilla javascript, however, in production, wiser use libraries moment.js.


Comments

Popular posts from this blog

networking - Vagrant-provisioned VirtualBox VM is not reachable from Ubuntu host -

c# - ASP.NET Core - There is already an object named 'AspNetRoles' in the database -

ruby on rails - ArgumentError: Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true -