Transforming precise military time using Angular and Javascript filtering

There are a few times where I find myself liking

01:45
//and
15:00

I believe this time format is HH:MM in military time?

While I have come across some advanced functions that can parse sentences and even include seconds like HH:MM:SS, I am looking for a simple and accurate way to extract just the HH:MM.

So if 15:00 is actually 3:00?

The function below won't work because there's already ":" assuming HHMM, right? But I think I need HH:MM to be parsed correctly?

var getTravelTimeFormatted = function (str) {
    var hours = Math.trunc(str / 60),
        minutes = str % 60;
        return hours + ':' + minutes;
    };

Update

So if I assume 15:00 is 3:00, correct?

I removed the ":" and then added it back, but the result is 25.0, so what does that mean?

var getTravelTimeFormatted = function (str) {
    str = str.replace(/:/g,'');
    var hours = Math.trunc(str / 60),
    minutes = str % 60;
    return hours + ':' + minutes;
};

console.log(getTravelTimeFormatted('15:00'));

Answer №1

If you have a string in the format HH:MM, you can easily split it and subtract 12 hours to convert it into a twelve-hour format. Below is a simple solution that does not handle invalid input scenarios.

function ConvertToTwelveHourFormat(time) {
    var timeParts = time.split(":");
    
    var hours = timeParts[0];
    var minutes = timeParts[1];
    var period = "AM";
    
    if (hours > 12) {
        hours = hours - 12;
        period = "PM";
    } else if (hours == "00") {
        hours = 12;
        period = "AM";
    } else if (hours == "12") {
        period = "PM";
    }
    
    return (hours + ":" + minutes + " " + period);
}

Answer №2

This code snippet provides a concise way to convert time from 24-hour format to 12-hour format using JavaScript. While the original answer was helpful, this function offers a more streamlined solution:

/* Function to convert time from 24 hour hh:mm format to 12 hour h:mm ap format
** @param {string} time - in hh:mm format (e.g. 14:30)
** @returns {string} time in 12 hour format (e.g. 2:30 PM)
*/
function convertTo12HourFormat(time) {
  var parts = time.split(/\D/);
  return (parts[0]%12 || 12) + ':' + parts[1] +
         (parts[0]<11? ' AM' : ' PM');
}

// Some test cases
['23:15', '2:15', '03:15', '00:30'].forEach(function(value) {
    console.log(value + ' => ' + convertTo12HourFormat(value));
});

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

The Markdown-to-jsx tool is having trouble processing the provided source code

Utilizing a Material UI blog post template found at https://github.com/mui-org/material-ui/tree/master/docs/src/pages/getting-started/templates/blog, I have created my React app using npx create-react-app. Upon console logging the source, it displays as a ...

Adding HTML content using jQuery's document.ready feature

As a jQuery novice, I am attempting to incorporate a Facebook like button using the jQuery document.ready function. In my external Javascript file (loaded after the jQuery script), you will find the following code snippet: $(document).ready(function(){ ...

Utilizing JavaScript for enhancing the appearance of code within a pre element

Is there a way to dynamically highlight the code inside a pre element using vanilla JavaScript instead of JQuery? I'm looking for a solution that colors each tag-open and tag-close differently, displays tag values in another color, and attributes with ...

Encountered an error while attempting to update an object: Unable to read property 'push' of undefined

Encountering an issue while attempting to update an object with additional information, receiving an error message stating 'property \'push\' of undefined'. /*Below is the object model in question:*/ export class Students { ...

The Jenkins build on a specific branch is encountering issues with path exporting, causing it to fail

I have a set of files related to a new feature that I am trying to deploy through Jenkins. I have successfully deployed other branches in the past, but I am encountering difficulties with a specific branch. https://i.sstatic.net/BKVbH.png I believe the pro ...

Choosing a versatile model field in a Django CMS plugin

Currently, I am developing a Django CMS plugin that includes a model choice field dependent on another field in the form. To update the choices in the model choice field based on the trigger field selection, I am using AJAX. However, when submitting the fo ...

Expo's ReactNative camera feature fails to flip the camera view

Following the guidance provided in Expo Docs on how to use a camera, I have noticed that when I press the flip button, the state of the camera type changes from 0 to 1 and vice versa, but the camera always remains on the back side. This is my implementati ...

We will explore the process of accessing a CSS file within an Angular

I'm having trouble reading a CSS file from my UI project directory in AngularJS. When I make a GET call, I only get the index.html file as output instead of the CSS file. Can anyone provide some guidance on how to properly access the CSS file? Any su ...

If the item with the specified name is not found in the list, display an image using Vue's v-if directive

<ul class="ulItems" v-for="item in listingItems" :key="item.channels"> <li class="liItems"> {{ item.itemName }} </li> </ul> I am looking to incorporate an image in situations where th ...

Enhancing User Experience with React-Redux: Implementing Subcategory Visibility based on Main Category Selection

How can I implement action logic to show and hide elements based on user interaction with main categories? Currently, all subcategories are being displayed at once, but I want them to be shown only when a user clicks on the corresponding main category. For ...

Is there a way to display a specific dropdown menu depending on the checkbox that is selected?

I have a bunch of checkbox items, including one labeled nocalls, as well as a couple of dropdownlist boxes. Here are the dropdown boxes: <tr> <td align="right"><FONT class="Arial10"><B>Profile<font color="#ff0000">*</ ...

Is it truly possible to return a reactive variable that updates its value asynchronously?

While reviewing the code of a frontend project developed in Vue3, I came across a unique construction that I have not encountered before. This has led to some confusion as I try to grasp how it operates. The concept involves assigning the result of an asyn ...

"Aligning the title of a table at the center using React material

I have integrated material-table into my react project and am facing an issue with centering the table title. Here is a live example on codesandbox: https://codesandbox.io/s/silly-hermann-6mfg4?file=/src/App.js I specifically want to center the title "A ...

Encountering a mixed content error in Internet Explorer 8 due to the Nivo slider jQuery?

I am encountering an issue with the Nivo jQuery slider on my HTTPS website, as it appears to be generating a mixed content error in Internet Explorer 8. Despite posting on the Dev7 Studios forum and conducting extensive research on the IE 8 mixed content ...

In Safari, there seems to be an issue where multiple URLs are not opening when clicked on from an anchor

Is there a way to open multiple URLs in Safari with just one click using window.open? I tried it, but only one URL opens in a new tab while the others do not. The version of Safari I am using is 11.0.1. onclick="window.open('URL1','_blank& ...

Tips for accessing the @keyframes selector and extracting the value from it

In my CSS code, I have a shape element with an animation that spins infinitely for 50 seconds. #shape { -webkit-animation: spin 50s infinite linear; } @-webkit-keyframes spin { 0% { transform: rotateY(0); } 100% { transform: rotateY(-360deg ...

Is Your CanvasJS Chart Traveling in Reverse?

My charts are displaying dates in reverse order, can anyone help me figure out what's causing this issue? I've checked the documentation but couldn't find anything that would explain this problem. Link to documentation: Here is a screensh ...

Having trouble setting up a successful connection with Socket.io client?

I'm struggling to integrate websockets into my website. Every attempt I make in the client results in errors. This is how I have Apache configured: <VirtualHost *:80> ServerName xxxxx.com DocumentRoot /var/www/html/RoW ErrorLog /var/www/html/Ro ...

Fetching JSON data using Promise.all results in an empty response

I'm facing an issue in my code where I am trying to fetch data from two different JSON files and then return them as arrays. Even after implementing the solution below, it doesn't seem to be working as expected. Can someone guide me on how I can ...

Searching for an item in an array within MongoDB: Tips and techniques

I am attempting to locate the object containing a specific element within an array: Here is my query: router.get('/', function(req, res) { var userSubscribed = req.user.email; db.posts.find({ "SubscriberList": { $elemMatch: userSubscrib ...