Learn how to extract values from an object in Vue JS time-slots-generator and display either PM or AM based on the

Using the time-slots-generator package, I am able to display the time from 0:15 to 24:00. However, the issue is that this package does not have built-in functionality to display AM/PM, so I had to create a manual solution for it.

To achieve this, I modified some code snippets found on StackOverflow and came up with the following implementation:

  
let hours = 23;
let minutes = 32;
let ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12; 
minutes = minutes < 10 ? '0'+minutes : minutes;
const strTime = hours + ':' + minutes + ' ' + ampm;
console.log(strTime)

If you change the values of hours to 17 and minutes to 25, the output will be 17:25 pm. The function logic is straightforward - it determines whether to display AM or PM based on the input value.

Now, my goal is to integrate this logic with my time generator. Currently, I am using a loop to display time from 0:15 to 24:00 as shown below:

  
data() {
  return {
    timeSlots: (ts.getTimeSlots([], true, "quarter")),
  }
},

formatAMPM() {
  let val = Object.values(this.timeSlots);
  for (let prop in val) {
    console.log(val[prop]);
  }
}

The current result of this loop can be seen here:

I now need to update the loop to display times in either AM or PM format. If you have a simpler solution or advice on how to implement this, I would greatly appreciate it. You can also view an example in codesandbox here.

Answer №1

One way to enhance your code is by encapsulating the time formatting logic within a separate function that can be easily reused:

export default {
  methods: {
    formatAMPM() {
      const formatTime = time => {
        const parts = time.split(':');
        let hours = Number(parts[0]);
        let minutes = Number(parts[1]);
        let ampm = hours >= 12 ? 'pm' : 'am';
        hours = hours % 12;
        hours = hours ? hours : 12; // ensure hour '0' displays as '12'
        minutes = minutes < 10 ? '0' + minutes : minutes;
        const strTime = hours + ':' + minutes + ' ' + ampm;
        return strTime;
      };

      Object.entries(this.timeSlots).forEach(([key, time]) => {
        this.timeSlots[key] = formatTime(time);
      });
    },
  }
}

Code Sandbox demo

Answer №2

If you are looking for a reliable and versatile solution for handling dates, consider using the date-fns' format function.

An example of its usage can be seen here: https://github.com/date-fns/date-fns/issues/946#issuecomment-452766765

By utilizing something like

format(new Date(), "hh:mmaaaaa'm'")
, you should have a solid and adaptable method at your disposal. Additionally, unlike Momentjs, this library is optimized and performs efficiently.

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 is the process for creating a clickable file upload in Angular?

Currently, I am utilizing the instructions found in this guide to implement a file upload feature in my project. The code provided works perfectly: <input type="file" class="file-input (change)="onFileSelected($event)" #fileUplo ...

Issue encountered when attempting to utilize multiple datasets with Twitter Typeahead/Bloodhound

Hello, I am currently learning how to use Typeahead and Bloodhound with the latest javascript. Below is a snippet of my code: Html: <div id="multiple-datasets"> <input class="typeahead" type="text" placeholder="NBA and NHL teams"> </div ...

Creating new Vue components is happening towards the end of the loop

I am currently encountering an issue with my Vue components. I have structured them in a hierarchy where I have a post-index component displaying all posts, containing a post-view component for individual posts, and within that, a post-like component to ha ...

How can I create clickable table entries using php and html?

I want to create a table on this page that is clickable. When the user clicks on a row, the data from that row will be sent to a PHP file with a form prepopulated with the selected user's information for updating purposes. <!DOCTYPE html> &l ...

Utilizing a Static Image Path Prop in React JS: A Step-by-Step Guide

My Main Component import React from "react"; import TopModal from "./components/topModal"; // Passing productImage to the Child Component import productImage from "../../../../../../assets/images/juices.jpg"; import { makeS ...

What causes the event parameter to be lost during recursion?

Below is the given code snippet: <html> <head> <meta charset="UTF-8"> <title>title...</title> <link type="text/css" rel="stylesheet" href="jquery-ui-1.10.4.custom.css" /> <script type="text/javascript" src="jq ...

Discovering Ajax-powered websites Here are some tips on identifying websites

My goal is to determine if a webpage makes AJAX calls. If the webpage is AJAX-based, I will wait for a few seconds to retrieve the content. If it's not AJAX-based, then I won't wait. I attempted the code below, but it didn't yield any resul ...

Is there a limit to the number of else if statements I can use? The final else statement

How can I enhance this code snippet? The last else if statement is not working, despite my efforts to fix it. var selectedDntTyp = $("#donationTypDD"); if (selectedDntTyp.length > 0) var DropInitValue = selectedDntTyp.val(); if(DropInitValue == &apos ...

What could be causing my AngularJS JSONP request to fail when trying to query Solr?

After attempting to query my Solr server with the provided code snippet: var url ="http://localhost:8080/solr/sdc/selectwt=json&callback=JSON_CALLBACK&q=opioid" $http.jsonp(url ).success(function(res){ console.log(res) }) An error is returned ...

provide an element reference as an argument to a directive

I am trying to figure out how to pass an element reference to a directive. I know that I can get the reference of the element where the directive is applied using private _elemRef: ElementRef but my goal is to pass the reference of another element to the ...

React Hooks encountering issues with keydown/up events functionality

Currently, I am in the process of implementing arrow-based keyboard controls for a game that I have been developing. In order to stay updated with React, I decided to utilize function components and hooks. To showcase my progress, I have put together a dem ...

Using NextJS to pass a string from an input field to getStaticProps via context

I am a beginner in NextJS and React, so please forgive my lack of knowledge. I am trying to figure out how to pass the text input by users from an input field (inside Header) to the getStaticProps function of a specific page using the React context API. I ...

How to efficiently pass props between components in NextJs

This is the project's file structure: components ├─homepage │ ├─index.jsx ├─location │ ├─index.jsx pages │ ├─location │ │ ├─[id].jsx │ ├─presentation │ │ ├─[id].jsx │ ├─_app.jsx │ ├─index.jsx ...

The art of replacing material-ui styles with styled components

As a newcomer to UI material design, I am eager to create my own customized Button Component using styled-components. I am facing a challenge in overriding the CSS based on different button variations such as "primary" or "secondary". You can find my cod ...

Tips for minimizing the transfer time of large arrays using ajax

https://i.stack.imgur.com/IP0oe.pngDescription I am currently working on transferring a JSON object from the server to the client using PHP and JavaScript via AJAX. The JSON object contains a large array (200x200) of integers. The server is running on lo ...

Local storage synchronization in progress, please hold on

Currently, there seems to be a synchronization issue between the local storage and the server. Countries, cities, and users are synchronized with the server separately through different Ajax calls. The problem at hand is that other JavaScript codes (such ...

Associating an object using checkboxes

I am facing a challenge in binding an object from checkboxes. In this specific scenario, each checkbox acts as its own component: <input type="checkbox" :value="option.id" v-model="computedChecked"> Below is the relevan ...

Utilizing two DTOs for a single controller in NestJS

I'm having trouble retrieving and transforming different types of dtos from the body. My goal is to extract and transform firstDto if it's incoming, or convert secondDto if that's what's being received. However, my current code isn&apos ...

React to the animated scaling

I'm attempting to animate the scale of my react component. Although it seems straightforward, I've run into some issues while following a similar example from the React-Motion demos: var customComponent = () => { let newStyle = { scale: sprin ...

When using props.onChange(e.target.value) in a textField component in Material UI, it unexpectedly returns an object instead of a value

function FormInput(props) { const classes = formInputStyles(); return ( <div> <TextField onChange={(e) => props.onChange(e.target.value)} InputProps={{ classes, disableUnderline: true }} {...pro ...