Attempting to convert numerical data into a time format extracted from a database

Struggling with formatting time formats received from a database? Looking to convert two types of data from the database into a visually appealing format on your page? For example, database value 400 should be displayed as 04:00 and 1830 as 18:30. Here's the code I'm using:

formatTime(time) {
    //Ensure at least three characters
    if (time.length > 2) {

      let firstDigits = time.substring(0, time.length - 2);  
      let lastDigits = time.slice(-2);  
      let formattedHour = (firstDigits.length > 1) ? firstDigits + ":" + lastDigits : "0" + firstDigits + ":" + lastDigits; 
      return formattedHour;
    } else if (time.length <= 2) {
      let firstDigits = '00';
      let lastDigits = time;
      let formattedHour = (lastDigits.length < 2) ? firstDigits + ":0" + lastDigits : firstDigits + ":" + lastDigits;
      return formattedHour;
    }
    return time;
  }

Expecting 400 to display as 04:00, 1830 as 18:30, but encountering issues. Any assistance would be greatly appreciated.

Answer №1

Have you thought about placing a zero at the beginning?

addZeroToTimeFormat(time) {
  if(time.length != 4){
    time = "0" + time;
  }
  return time.substring(0, 2) + ":" + time.substring(2)
}

You might want to explore using date formats and the angular date pipe for better options.

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

I encountered an issue where I could not successfully update a list pushed into an array using the push function. Despite attempting to update the list, I

export class ApproveComponent implements OnInit { @Output() public next: EventEmitter<any> = new EventEmitter<any>(); codes: any[] = []; selectedCode: any; this.Apiservice.komm.subscribe(data => { this.se ...

Change a nested for-loop into an Observable that has been transformed using RxJS

Currently, the following function is operational, but I consider it a temporary solution as I'm extracting .value from a BehaviorSubject instead of maintaining it as an observable. Existing Code Snippet get ActiveBikeFilters(): any { const upd ...

Issue with resolving symbol JSON in Angular 7 when using JSON.stringify

Let me start off by saying that I am new to Angular 7. Currently, I am in the process of developing an application using Angular 7 with a C# backend. The specific challenge I am facing is the need to serialize an object in my component/service before sendi ...

The `findOne` operation in Mongoose fails to complete within the 10000ms time limit

Encountering this error on an intermittent basis can be really frustrating. I am currently using mongoose, express, and typescript to connect to a MongoDB Atlas database. The error message that keeps popping up reads as follows: Operation wallets.findOne() ...

Function that sets object properties based on specified keys and verifies the value

Let's consider a scenario where we have an object structured like this: interface Test{ a: number; b: string; c: boolean; } const obj:Test = { a: 1, b: '1', c: true, } We aim to create a function that can modify the value ...

Creating a method to emphasize specific words within a sentence using a custom list of terms

Looking for a way to highlight specific words in a sentence using TypeScript? We've got you covered! For example: sentence : "song nam person" words : ["song", "nam", "p"] We can achieve this by creating a custom pipe in typescript: song name p ...

Component unit testing in Angular 2/4 fails to register click events causing a lack of change detection

I'm currently working on testing a component in Angular 2/4 to determine if clicking on a button element will result in the desired changes. However, I'm facing an issue with triggering the click event. Here is the component code: import { Comp ...

What steps can be taken to disable auto correction in ngx date picker?

In my application, I am utilizing ngx-datepicker with 'DD.MM.YYYY' as the dateInputFormat in the configuration settings of the date picker. The challenge arises when I manually input a date following the format 'YYYY.MM.DD', as the ente ...

I encountered an error with Firebase when attempting to run functions on my local machine

Encountering a Firebase error when running the function locally using emulator in CLI $ firebase emulators:start --only functions Initiating emulators: ["functions"] functions: Using node@8 from host. functions: Emulator started at http://localhost:50 ...

Display Bootstrap Modal Box automatically when Angular 8 App Loads

I am facing an issue with launching a modal dialog on page load in my Angular 8/Visual Studio project. While it works perfectly fine with the click of a button, I am unable to make it load automatically on page load. I have tried using *ngIf but it doesn&a ...

The table is appearing incorrectly on the screen

I am working on displaying a list of elements in a table. To achieve this, I have created two components - the tableComponent and the tableitemComponet. In the tableComonent, I have implemented the following: <table class="table"> <thead> ...

Font Awesome functions properly on one Angular component but not on the second one

I've encountered a strange issue while working on my Angular project. About a month ago, I added a component with a form that included some inputs along with Font Awesome icons. The code snippet is provided below. <div class="field"> ...

Ionic 3: Struggling to Access Promise Value Outside Function

I've encountered an issue where I am unable to retrieve the value of a promise outside of my function. It keeps returning undefined. Here's what I have attempted so far: Home.ts class Home{ dd:any; constructor(public dbHelpr:DbHelperProvider ...

The specified default path for an outlet in Angular

How can I set up the routes in this module to ensure that when the application loads, it will route to CComponent. Additionally, I want the AComponent to be loaded in the named router outlet search-results. app.module.ts import { BrowserModule } from &apo ...

What is the process for downloading the array of images' responses?

Currently, my setup involves Angular 5 on the front end and Spring Boot on the backend. I am facing the challenge of downloading the JSON response of images. Can anyone provide guidance on how to achieve this? ...

Ensuring that the app closes completely before launching a new instance with webpack hot module reload

My nest.js application is utilizing webpack hot module reload (hmr), but I am encountering an issue where the reload does not allow the old instance to fully close (including the database connection and telegram bot) before launching a new instance. This c ...

Unable to dynamically add an element to a nested array in real-time

I'm currently developing an angular tree structure that contains a large nested array. nodes : public fonts: TreeModel = { value: 'Fonts', children: [ { value: 'Serif - All my children and I are STATIC ¯\ ...

React/Typescript - Managing various event types within a unified onChange function

In my current project, I am working with a form that includes various types of input fields using the mui library. My goal is to gather the values from these diverse input components and store them in a single state within a Grandparent component. While I ...

Explaining how to use the describe function in TypeScript for mapping class constructors

I am working on a function that will return a JavaScript Object with the class instances as values and the class names as keys. For example: const init = (constructorMap) => { return Object.keys(constructorMap).reduce((ret, constructorName) => ...

When publishing an Angular library using npm, you can exclude a specific folder while still including all of its files and sub-folders in the

After building my angular library app, I find the artifacts stored in the directory dist/. This means that when the library is imported into another application, it is done like this: import { XXX } from 'libname/dist' However, I wish to have th ...