Scrape JSON Data and Convert Military Time to Standard Time Using JavaScript

I have a question about scraping JSON data from a URL. The timestamps are in military time and I'm looking for a way to convert them to standard time on the client side.

Here is the JSON snippet:

[
  {
    SaturdayClose: "21:00",
    SaturdayOpen: "10:00",
    SundayClose: "12:00",
    SundayOpen: "18:00",
    WeekdayClose: "21:00",
    WeekdayOpen: "10:00"
  }
]

This is my index.html file:

    <p>
        Sun: ${ SundayOpen }a - ${ SundayClose }p Mon - Sat: ${ SaturdayOpen }a ${ SaturdayClose }p
    </p>

However, the output looks messy:

Sun: 18:00a - 12:00p Mon - Sat: 10:00a 21:00p

I would prefer it to look like this:

Sun: 6:00a - 12:p Mon - Sat: 10:00a - 9:00p

Answer №1

By implementing a date script, you can easily convert time from the 24-hour clock to a 12-hour format. This involves subtracting the hours and adding the appropriate period.

MORE INFORMATION:

To test this functionality, I included two times: 00:30, which should become 12:30 am, and 12:15, which should be represented as 12:15 pm. Please refer to the updated details below.

var times = {
    SaturdayClose: "21:00",
    SaturdayOpen: "10:00",
    SundayClose: "12:00",
    SundayOpen: "18:00",
    WeekdayOpen: "10:00",
    WeekdayClose: "21:00",
    WeekendOpen: "12:15",
    WeekendClose: "00:30"
};

console.log(times);

for (var time in times) {
    var parts = times[time].split(':'),
        hour = parts[0],
        minutes = parts[1];

    if (hour > 12) {
        times[time] = (hour - 12) + ':' + minutes + ' pm';
    } else if (hour == 0) {
        times[time] = 12 + ':' + minutes + ' am';
    } else if (hour == 12) {
        times[time] += ' pm';
    } else {
        times[time] += ' am';
    }
}

console.log(times);

http://jsfiddle.net/tqXCL/3/

After applying the conversion process, the output is as follows:

SaturdayClose "9:00 pm" 
SaturdayOpen  "10:00 am"    
SundayClose   "12:00 pm"    
SundayOpen    "6:00 pm" 
WeekdayClose  "9:00 pm" 
WeekdayOpen   "10:00 am"    
WeekendClose  "12:30 am"    
WeekendOpen   "12:15 pm"

Answer №2

If you prefer using HTML over JSON, follow these steps.

dateEl.innerHTML=dateEl.innerHTML.replace(/(\d\d)(:\d\d[ap])/g,function(m,hour,suffix) {
  return (+hour+11)%12+1+suffix;
});

Please ensure that dateEl is set to the correct element and does not contain any other time formats that should not be converted.

Answer №3

Check out date.js. This website offers a plethora of useful date conversion tools.

Answer №4

VIEW DEMO

window.addEventListener('load', function() {

  var regex = /(\d{2}:\d{2}[ap])/gi;
  var timeText = document.getElementById('times').innerHTML;
  var matches = timeText.match(regex);
  
  for (var j=0; j<matches.length; j++) {
    var partsArr = matches[j].split(":");
    var hourValue = parseInt(partsArr[0],10);
    
    if (hourValue > 12) partsArr[0] = hourValue - 12;
    else if (hourValue === 0) partsArr[0] = 12;
    
    timeText = timeString.replace(matches[j],partsArr.join(":"));
  }
  
  document.getElementById('times').innerHTML = timeText;
});

Answer №5

Converting "Military time" (also known as 24-hour time) to 12-hour time is a straightforward process using a simple modulo 12 operation.

Check out this JSFiddle example for clarification:

var obj = {
    SaturdayClose: "21:00",
    SaturdayOpen: "10:00",
    SundayClose: "12:00",
    SundayOpen: "18:00",
    WeekdayClose: "21:00",
    WeekdayOpen: "10:00"
}, prop, $output = $('#output'), time, x, meridiem;

for (prop in obj) {
    if (obj.hasOwnProperty(prop)) {
        x =+obj[prop].substr(0, 2);

        if (x > 12) {
            x = x % 12;
            meridiem = "pm";
        } else {
            meridiem = "am";
        }

        time = x + ":00" + meridiem;

        $output.append("<li>" + prop + " " + time + "</li>");
    }
}

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

What could be causing this axios.get request to fail?

I am currently enrolled in Colt Steele's Web Developer bootcamp and facing a challenge... In the tutorial, we are using axios as 'request' has been discontinued, so I am trying to follow along with this change. My goal is to set up a Get r ...

What might be causing my enzyme test for React to fail when calling document.getElementById()?

I am currently facing an issue while trying to render a Snapshot test for a nested React component. The problem lies with the test code failing to handle a document.getElementById() request within the component's relevant code section: componentDid ...

How can I retrieve the array data that was sent as a Promise?

I have a database backend connected to mongoDB using mongoose. There is a controller that sends user data in a specific format: const db = require("../../auth/models"); const User = db.user const addProduct = (req, res) => { User.findOne({ ...

An error occured upon loading FullCalendar: Uncaught TypeError - Unable to read property 'push' as it is undefined

First of all, thank you for your assistance. I've been trying to load FullCalendar (https://fullcalendar.io/) on my development environments but it doesn't seem to be working. When I check the console in Chrome, it shows me the following error m ...

In the strict mode tree, a reference named "grid" has been discovered

I encountered the following warning in the console: Warning: A string ref, "grid", has been found within a strict mode tree. String refs can potentially lead to bugs and should be avoided. It is recommended to use useRef() or createRef() instead. T ...

Troubleshooting issue with Onchange in select HTML element within Django

I'm working with a Problems model in my project. In my Models file models.py class Problems(models.Model): Easy = 'Easy' Medium = 'Medium' Hard = 'Hard' NA = 'NA' DIFFICULTY = [ (NA ...

What is the method to trigger the jQuery 'mouseenter' event on an element using Selenium?

Struggling to automate a scenario using selenium where I need to click on a menu element. I've tried various methods, except jQuery. WebDriver normal click and JavaScript click() haven't worked. Can someone assist me with implementing jQuery in s ...

"Resetting select fields in a Django application using jQuery: A step-by-step guide

Recently, I was tasked with taking over a partially-developed Django application. Python is familiar territory for me, but I am completely new to JavaScript. This application heavily relies on jQuery for various form manipulations. One specific issue I enc ...

What is the best jQuery library to add to my website?

I have included several jQuery scripts on my website for various functionalities such as sticky header, anchors, and animations. I am wondering if it is necessary to include all of them or if I can just include one or two? Here are the jQuery scripts I ha ...

Utilize grep and sed commands to extract information from a JSON file

I have a file in the json format called output.json. It contains data in a simple key:value structure, similar to this: { "key":"value", "key":"value", "key":"value", "key":"value", } My goal is to retrieve the "value part" from this file ...

Retrieving public Twitter posts using JSON format

Looking to access the Twitter database for public tweets using JSON and jQuery? Check out this function I wrote: $(document).ready(function(){ alert("1"); $("button").click (function(){ alert("2"); $.getJSON("http://search.twitter. ...

Tips for toggling the visibility of a revolution slider based on current time using JavaScript

Currently, I am integrating the revolution slider into my WordPress website. My goal is to have the slider change according to the standard time of day. For instance, I want slider1 to display in the morning, slider2 at noon, slider3 in the evening, and sl ...

Using pdfkit to create a PDF and then returning it as a base64 string from a function

I am attempting to utilize PDFKit to produce a PDF file and then retrieve it as a base64 string. Here is the code snippet I am using: function generatePDFDocument(data){ let doc = new PDFDocument(); var bufferChunks = []; doc.on('readabl ...

Storing JSON data in SQL Server

Is there a way to eliminate spaces using the given query? The second input value (" DEF") and third input value ("GHI ") contain extra spaces. How can we remove these spaces? Here is the original query: SELECT * FROM openjson('[{"value":"12 ...

Integrate the perfect-scrollbar jQuery plugin into RequireJS

Recently, I decided to explore RequireJS for my projects but I am still trying to understand its functionalities. I'm currently attempting to incorporate perfect-scrollbar, specifically the jQuery version, into my work. Here's a snippet from my ...

Displaying JSON data via AJAX, the APIKEY has been concealed to ensure security measures are upheld

How can I fetch the JSON array and print it using the $.each function with AJAX code included? I have hidden my APIKEY for security reasons, and I am certain that there is no error in getting the JSON response. I have checked the console log and confirmed ...

Struggling to Implement Middleware on Router in ExpressJS?

In my application, I have both public and authenticated routes. The isAuthenticated function is used, for example, in a news controller. globalRouter: function (app) { app.use((req, res, next) => { logger.log("Endpoint: ", req.originalUrl); n ...

How can I obtain an array using onClick action?

Can anyone help me figure out why my array onClick results are always undefined? Please let me know if the explanation is unclear and I will make necessary adjustments. Thank you! Here is the code snippet: const chartType = ["Line", "Bar", "Pie", " ...

Retrieve all posts from a specific category on a WordPress website using Node.js

Is there a way to retrieve all articles from the "parents" category on a WordPress website without just getting the html of the page? I need the full text of each article, not just a link with a "read more" button. I have tried using the nodejs plugin "w ...

Error message: "An undefined index error occurred during an Ajax call to a

Path: homepage -> initiate ajax request to tester.php on PHP -> receive JSON data back to homepage. I am struggling to resolve this issue. Any help would be appreciated. AJAX Request: $.ajax({ url : "tester.php", ty ...