Transform Vue military time to regular time format

I am retrieving the arrivalTime from todos.items. As I fetch the arrivalTime, it is sorted using the sortedArray function(), which converts the times to military time. Is there a way to change the sorted military time values to standard time format after sorting?

View

<div id="app">

  <div v-for="todo in sortedArray">
    {{ todo.items.arrivalTime }}
  </div>
   <!-- Can we convert todo.items.arrivalTime into paragraph tags like below -->
  <br>
  <h1>
    <b>Convert Into</b>
  </h1>
  <br>
  <p>09:00 AM</p>
  <p>10:00 AM</p>
  <p>11:00 AM</p>
  <p>02:00 PM</p>
  <p>10:00 PM</p>

</div>

Script

new Vue({
  el: "#app",
  data: {
    todos: [
      { id: "1", items:{arrivalTime: "1100"} },
      { id: "2", items:{arrivalTime: "1000"} },
      { id: "3", items:{arrivalTime: "1400"} },
      { id: "4", items:{arrivalTime: "0900"} },
      { id: "5", items:{arrivalTime: "2200"} },
    ]
  },
  methods: {
    toggle: function(todo){
        todo.done = !todo.done
    }
  },
  computed:{
    sortedArray: function() {
      console.log("inside sortedArray");
      function compare(a, b) {
        if (a.items.arrivalTime < b.items.arrivalTime)
          return -1;
        if (a.items.arrivalTime > b.items.arrivalTime)
          return 1;
        return -1;
     }
      return this.todos.sort(compare);
    }
  }
})

I attempted converting military time to standard time using jsFiddle, but encountered difficulties. Here's my code on JsFiddle for reference.

https://jsfiddle.net/ujjumaki/m2sowbv9/19/

Answer №1

My solution closely resembles the one mentioned above, but it offers better performance.

Link to the code snippet

fromMilitaryTimeFormat: function(time){
      if(parseInt(time) <= 1259){
       return `${time.slice(0,2).padStart(2, '0')}:${time.slice(2).padStart(2, '0')} AM`
      }else if (parseInt(time) >= 1300 && parseInt(time) <= 2359){
        let convert = parseInt(time) - 1200
        let temp = convert.toString()
        return `${temp.slice(0,1).padStart(2, '0')}:${temp.slice(2,3).padStart(2, '0')} PM`
      }
    }

Answer №2

While this information is not directly related to Vue.js, it pertains to JavaScript in a general context.

If you are seeking a solution, one approach would involve breaking down the military time string into individual characters and then utilizing a Date object for comprehensive details.

var hrs, min, result, time;

time = '1100';

hrs = time.slice(0, 2);
min = time.slice(2, 4);
console.log(hrs, min);

result = new Date;
result.setHours(hrs);
result.setMinutes(min);
console.log(result);

This method yields a complete Date object which can be further formatted using libraries like date-fns.

Alternatively, if the requirement does not involve additional time calculations or date specifics, direct manipulation of the military time string can suffice.

var hrs, min, result, time;

time = '1100';

hrs = time.slice(0, 2);
min = time.slice(2, 4);

if (parseInt(time) > 1259) {
  result = `${hrs - 12}:${min} PM`;
} else {
  result = `${hrs}:${min} AM`;
}

console.log(result);

Please note that the above example may not be entirely accurate. For instance, the interpretation of 12:59 as either AM or PM can vary depending on cultural conventions.

Best wishes and good luck!

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

Generating additional react-select dropdowns depending on the selection made in the initial dropdown menu

I am currently working on a travel website. I am in need of a dropdown menu for users to select the number of children they will be traveling with, with options for 1, 2, or 3. If the user chooses 1 child, then an additional react-select element should ...

Receiving and monitoring events triggered by a Vue component that was dynamically mounted

I am currently mounting a Vue component dynamically within a mixin to incorporate the resulting HTML into a map popup. While everything is functioning correctly, I am facing an issue with listening to events emitted by the component. I am unsure of how to ...

Transfer information from a single form and distribute it across multiple forms with the help of jQuery or Javascript

Form1 has a variety of input fields including text, select, radio, and textarea. At the bottom there is a button labeled "copy" that allows users to copy data from all the fields in Form1. In different pages, I have three to four other forms with input fi ...

Creating beautiful prints with images

I have been tasked with developing an MVC C# application where the contents of a div are dynamically created using an AJAX call to fetch data from a database. Upon successful retrieval, the content is then displayed as a success message in JavaScript. Here ...

Ways to conceal buttons according to your 'occupation'?

I am currently developing an application and I would like to have certain buttons displayed based on the user's $job. There are four job roles stored in mysql databases: student teacher staff principal, The signup button should only be visible to te ...

Using the power of jQuery, execute a function only once when the element is clicked

My goal is to use jQuery's .one method to change the color of an element only once, even if clicked again. However, I am having trouble getting it to work properly. Here is my HTML: <!DOCTYPE html> <head> <meta charset="UTF-8"& ...

Encountering Uncaught Promise Rejection Warning in Node.js

I can't figure out why I am receiving this error or warning when my code appears to be correct. Below is a snippet of the UserModel that I have been working on: const fs = require('fs'); class UserModel { constructor(filename) { ...

Parsing JSON data into different data types in C#

I am looking for a way to transfer various types of data from JavaScript to C#. Specifically, I want to send a JSON object from the JavaScript side using an AJAX call. Here is an example: AnObject = new Object; AnObject.value = anyValue; $.ajax({ typ ...

Utilize D3's pie chart to showcase the data in JSON's individual collections

I am currently working on creating a pie chart that displays the distribution of collections based on their names. I have come across an issue where d3.layout.pie().value() only evaluates specified array values. Is there a solution available to extract the ...

Encountering an error with $mdDialog.alert

I am attempting to activate an Alert Dialog using Angular Material Design. Within my controller, I have: angular.module('KidHubApp') .controller('ActivityCtrl', ['$scope','$meteor', '$stateParams', &apo ...

Issue with NPM identifying my module (demanding unfamiliar module)

Currently, I am developing a React-Native application and organizing my components into separate files. Most of the time, this method works perfectly fine except for one specific instance where I keep encountering a 'Requiring unknown module' err ...

The post request is successful in Postman and cURL, however, it faces issues when executed in Angular

A remote server and a local client are set up to communicate through a simple post request. The client sends the request with one header Content-Type: application/json and includes the body '{"text": "hello"}'. Below is the s ...

The Else clause is executing twice in the jQuery code

https://jsfiddle.net/mpcbLgtt/2/ Creating a function that adds card names to an array named deck and their IDs to another array called cardIds when a div with the class "card" is clicked. The cards available are: <div class='card' id=' ...

I am unable to access the Dynamsoft ResourcesPath

Dynamsoft.DWT.ResourcesPath = "dwt-resources" Package.json "scripts": { "dev": "ncp node_modules/dwt/dist static/dwt-resources && nuxt", "build": "nuxt build", "start": &q ...

Challenges in Implementing Shadows with Animations in ThreeJS MeshDepthMaterial

I'm facing an issue where casting shadows through transparent parts of my Mesh using the MeshDepthMaterial causes the shadows of animated objects to stop moving along with the animation. You can see an example of this problem here: https://jsfiddle.n ...

What is the best way to save high-resolution images created with HTML5 canvas?

Currently, there is a JavaScript script being used to load and manipulate images using the fabricjs library. The canvas dimensions are set to 600x350 pixels. When smaller images are uploaded onto the canvas and saved as a file on disk, everything works c ...

Can you group polygons in layers using Phaser?

My goal is to animate two polygons: one that remains stationary and another that changes shape while moving. The challenge is to ensure that the stationary polygon always stays on top when overlapping. This is my proposed solution: (function() { "use ...

Loop through the JSON data and dynamically display corresponding HTML code based on the data

I've developed a survey application using React, where I initially wrote code for each question to display radio buttons/inputs for answers. However, as the survey grew with multiple questions, this approach resulted in lengthy and repetitive code. To ...

Troubleshooting the "@material-ui/core" issue in React: Step-by-step guide

Issue with React: Unable to locate the '@material-ui/core' module in 'C:\Users\user\Downloads\inTech'22-Web Development (EDUGEN)\edu-gen\src\components' Resolution Command: To resolve, run npm in ...

Deciphering Google location data using JavaScript

It appears that this code is not functioning properly for unknown reasons let url = "https://maps.googleapis.com/maps/api/place/search/json?"; url += "location="+lat+","+lng+"&"; url += "radius=500&"; url += "types=&"; url += "name=&"; url ...