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:https://i.sstatic.net/X3xdG.jpg

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

Utilizing Lodash efficiently with tree shaking

After experimenting with using lodash functions as a specific import versus as a destructured object, I noticed a significant difference in file size. When imported as shown below, the size is only 14.7KB. However, when I tried importing as a destructured ...

Is there a way to position the icon in the top left corner within the image using Vue and CSS?

I am currently working on a Vue project and I am attempting to create a row of images with an icon positioned at the top left corner of each image. Here is my code snippet: <div v-for="(image, index) in images" :key="index" class=&q ...

Accessing database values for dropdown menus using JavaScript

Please provide guidance on how to populate a dropdown with values from a database in this code snippet, which is used to create dynamic rows in a table. <script type="text/javascript"> $(document).ready(function(){ $(".add-row").click(function() ...

I am finding the module.export feature in Express JS to be quite perplex

I recently started learning Express JS with the EJS templating engine, using express-generator to set up my project. I only made a few modifications to the initial code. In the directory structure of my app: MyApp->routes->index.js var express = re ...

You can use AJAX, JQuery, or JavaScript in PHP to upload a total of 7 files by utilizing 7 individual file input

My client has a unique request - they want to be able to upload a file in PHP without using the traditional <form> tag or a submit button. While I am familiar with file uploads in PHP, I am unsure of how to achieve this without utilizing the <for ...

A guide to organizing page components across multiple `/pages` directories in a Next.js application

As I delve into my first project using Next.js, I find that my pages directory has expanded significantly. Now, I am keen on organizing my pages by grouping them into modules, resulting in a structure like 'src/modules/*/pages/*'. In my quest fo ...

Incorporating a vuejs component within another for enhanced functionality

Within my app.js file, I have the following code: import MenuItem from './components/MenuItem.vue' import NavMenu from './components/NavMenu.vue' new Vue({ el: '#app', components: { 'nav-menu' : NavMe ...

Adjust the object's width and position based on the window's width

I am currently attempting to adjust the width of a box and the position of a btn based on the size of the window. Q1. How can I eliminate the excess white space located behind the scroll bar? (I have already set it to 100%..) Q2. After clicking the ...

TS: How can we determine the type of the returned object based on the argument property?

Assume we have the following data types type ALL = 'AA' | 'BB' | 'CC'; type AA = { a: number; }; type BB = { b: string; }; type CC = { c: boolean; }; type MyArg = { type: ALL }; I attempted to create a mapping between type n ...

Issue with vue-template-compiler in Vue.js 3 webpack configuration

I am currently working on integrating vuejs 3 into a project that already utilizes webpack. I have been looking into using vue-loader as part of this process. After consulting the official documentation, I came across the following information: Every new ...

Tips for maximizing website performance on touch-enabled devices

When using a touch device such as an iPhone, iPad, or Android device, it can be challenging to accurately tap on small buttons with your finger. So far, there is no universal method in CSS media queries to detect touch devices. As a workaround, I check if ...

"My JavaScript code for toggling visibility is not functioning properly. Any suggestions on how to fix

I am currently working on a task that involves showing and hiding container1, but I am confused as to why my code is not functioning properly. The task requirements are as follows: - Clicking on the "Show" button should display container1 - Clicking on the ...

Troubleshooting: Issue with Angular 2 bidirectional data binding on two input fields

Hi there, I am encountering an issue with the following code snippet: <input type="radio" value="{{commencementDate.value}}" id="bankCommencementDateSelect" formControlName="bankCommencementDate"> <input #commencementDate id="bankCommencementDat ...

Using a string as a key for an object's property

function createObject(argName, argProperties){ var object = {}; object[argName] = argProperties; } I am calling my function in the following manner. createObject('name', objectProperties); The issue I am encountering is w ...

Vue Progress Bar service

When working with Angular, I typically utilize a dedicated class to manage the progress bar functionality. By intercepting HTTP requests and routing requests, including GraphQL requests like so: loading-indicator-service import { Injectable } from &apos ...

Using Vuex as a global event bus ensures that all subscribers will always receive notifications for

For a while now, I have relied on a global event bus in Vue - creating it as const bus = new Vue(). It works well, but managing subscriptions can get tedious at times. Imagine subscribing to an event in a component: mounted() { bus.$on('some.event ...

Can we include intricate items within a redux store?

As I delve into developing a React application with Redux, I encountered an unexpected scenario. At one point, we inserted a DOM element within the store, causing issues with the Redux extension that freezes when the action is triggered. Despite this compl ...

I am encountering an issue where I am sending an AJAX request to a PHP file with the datatype set as JSONP, but I

When I click on the submit button, I am sending a variable to sendmail.php. However, PHP is showing that 'contactname' is undefined. Why is this happening? Here is the code snippet: var name = document.getElementById('stream_cotactname&apo ...

All Pages Except Index in Vue Website Report "404 Error: /path Not Found"

Using Vue with Node.js to host my website on an AWS EC2 instance. I don't have a main index node.js file, just the vue-router file. Utilizing AWS CloudFront to secure my certificate and traffic. The issue arises when accessing the site through the ser ...

React Native Function fails to return a value

Within my React Native app, there's a page called RepsPage that displays a scroll view using an array of IDs. I'm passing this array to a function named renderRep, attempting to create a view for each item in the array. However, the return statem ...