Generating random time in JavaScript: A step-by-step guide

Looking to generate a random time in the format "HH:MM AM" within my selenium IDE using JavaScript.

Attempted code: javascript{Math.floor(24*Math.random() + 00) +":" + "00 PM";}

Unfortunately, this code is not functioning as expected. Any assistance would be greatly appreciated. Thank you.

Answer №1

Shehryar's response may not generate truly random results due to the method used - it should be multiplying by 12 for hours and 60 for minutes, rather than using the current numbers. As a result, higher hour and minute values will occur less frequently. Additionally, there is a chance of obtaining zero hours and 60 minutes due to rounding instead of flooring the values.

The structure of the HTML document and the use of the document object are well done, so I will replicate that:

<div id="timebox"></div>
<script>
function pad(number) { 
  //Add a leading 0 if number is less than 10
  return ((number<10)?"0":"")+number.toString();
}

function randomTime() {
  //Generate a random minute in a day (1440 minutes in 24 hours)
  var r = Math.floor(Math.random() * 1440);

  //Calculate the hour by dividing by total minutes per hour, taking floor value 
  //then getting remainder after dividing by 12 (13 -> 1) and adding 1 for range 1-12
  var HH = pad(1 + (Math.floor(r/60) % 12));

  //Get integer remainder after dividing by 60 (remove hours part)
  var MM = pad(r % 60);

  //Decide between AM and PM based on time
  var AMPM = (r>=720) ? "PM" : "AM";

  return HH + ":" + MM + " " + AMPM;
}

document.getElementById("timebox").innerHTML=randomTime();
</script>

Answer №2

Have you checked out this post for guidance on formatting JavaScript dates: How to format a JavaScript date and also explored the Date object documentation here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date These resources might help you find a solution. Best of luck!

UPDATE: I've created a jsFiddle to assist you, check it out here: http://jsfiddle.net/damf9hf1/3/

Here's the HTML code snippet:

<div id="timebox"></div>

And the JS code snippet:

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;
}
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"Keep the div locked to the screen when the bottom of the div aligns with the

Hey everyone! I'm currently grappling with a project that requires me to keep a div stuck to the screen (prevent scrolling) when its bottom reaches the bottom of the screen. I have two divs on the page, both with varying heights. My aim is to keep div ...

Tips on how to round a whole number to the closest hundred using Javascript

Suppose there is a numerical value given let x = 890 and the objective is to round it off to 900. If the number is 820, then it should be rounded to 800. We can safely assume that the input number (x) will always be an integer. While manually checking ...

``The importance of properly formatting a text string before encoding it into

Currently in the process of converting an XML document to JSON via a PHP backend and then sending it back to the frontend using AJAX. This is achieved through the following code snippet: print_r(json_encode($result_xml)); If you want to view the response ...

Creating a multi-tiered dropdown menu in the navigation bar with the help of Bootstrap 4 and Angular 7

My goal is to implement a multilevel dropdown using bootstrap 4 and angular 7. While I successfully created a simple dropdown in the navbar following the official bootstrap documentation, I struggled to make the multilevel dropdown work. After referring ...

Clicking on a button will trigger the opening of a modal dialog

I encountered an issue with the following code: <sepa-modal ref="sepaModal" /> <b-card id="show-btn" class="card-modal" @click="openSepaModal()" > </b-card> openSepaModal ...

Is there a way to use Selenium (Java) to scroll a div with overflow?

Is there a way to scroll down an overflow div using Selenium (Java)? I want to scroll within a specific div element rather than the browser window. I tried: JavascriptExecutor jse = (JavascriptExecutor) driver; jse.executeScript("getElementByXpat ...

Applying autocomplete (Jquery) functionality to dynamically loaded partial views using AJAX in MVC4

I have a situation where I need to create Project models with a table of company-related data. To achieve this, I have implemented a button that triggers an AJAX call to fetch a partial view and add it to the table: $("#addCompanyRoleProject").click(funct ...

`The challenge of properly handling quotation marks within quotation marks in JavaScript string literals

I am having trouble displaying text in a JavaScript tooltip Despite my efforts to escape the quotes and eliminate any line breaks, I keep encountering unterminated string literals. The specific text I want to show is: "No, we can't. This is going t ...

Employing the Map function in React leads to an error that is undefined

Upon simplifying my code, it seems that I am encountering an unresolved issue with the map function being used in different locations. I have noticed that code from examples running on platforms like Codepen does not work in my locally created react app p ...

What is the reason for requiring shaders to reside in an HTML file for a WebGL program?

In a recent forum thread, an individual posed the question about how to eliminate shaders from html. The discussion revolved around finding alternatives to embedding shaders in webGL code: WebGL - is there an alternative to embedding shaders in HTML? The ...

Is it possible for Skycons to show a duplicate icon?

My current issue involves integrating the JavaScript plugin "Skycons" with the Yahoo weather RSS feed. The problem arises when multiple days have the same weather forecast, as the plugin retrieves icons based on ID rather than class. This prevents me from ...

What is the best method for adding a header to a dynamically created table using JavaScript?

After receiving JSON data in my JavaScript, I have successfully converted it into an HTML table. Everything seems to be working fine, but I'm wondering how I can add a header to my table? Below is the code snippet: <script> $(document ...

arranging data in various categories with React.js

Can anyone figure out why this code is struggling to properly sort based on columns? sort(key){ this.setState({ [`toggle-${key}`]: !this.state[`toggle-${key}`], data: sortBy(this.state.data, [key], this.state[`toggle-${key}`]).map(v => ...

What is the best way to iterate over an indexed attribute in PHP?

Here is my ajax code snippet: $.ajax({ type: "POST", url: "bee_sesi_edit.php", data: 'serv_ruang='+ serv_ruangx +'&who='+names +'&sesi_d1='+ sesi_d1 +&apos ...

Enhancing Dropdown Selections with Jquery and AngularJS

Is there a way to dynamically change the options in this dropdown menu? For example, could I update it to show <li><a data-action="100">100</a> when another button is clicked using ng-click()? <ul class="dropdown-menu pull-right" r ...

Return all HTML code from the Ajax element

I can't seem to pinpoint the issue with my code. When I make an ajax call using the code below: ajax.js: function ajaxObj(meth, url){ var x = new XMLHttpRequest(); x.open(meth, url, true); x.setRequestHeader("Content-type", "application/x-www_form-u ...

Printing in HTML with Angular based on certain conditions

As I cycle through a list of products, I am verifying if the product Id is already included in an array of products (objects). If it is, then I print the quantity. If not, I attempt to print 0. Here is the code snippet I have been working on: <ion-item ...

Extracting information from JSON using arrays

I'm facing a bit of a challenge with this one. I've been trying to use jQuery on my website to update an element. It works perfectly fine without using an array of data in JSON, but as soon as I introduce an array of data, it stops functioning. I ...

There seems to be a lack of response from the Foursquare API in Node.js

Seeking guidance on retrieving a photo from a Foursquare venue using Node.js platform. Despite having the correct id and secret, the code is returning an unexpected result. My goal is to obtain the prefix and suffix of the image to properly display it as o ...

Creating a Chart.js line plot with discontinuous sections (jumps)

Using Chart.js, I have created a line chart and am looking to avoid rescaling the x-axis for more sample points. What is the most effective method to showcase jumps when y axis values change abruptly? Ideally, I want to be able to assign two y values per ...