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

Accessing different pages in Angular 2 based on user type

If I have four pages and two user types, how can we implement access control in Angular 2 so that one user can access all four pages while the other is restricted to only two pages? ...

Flex: 1 does not completely fill the Angular layout div in vertical dimensions

I am currently developing a sidebar using Angular and Flex. The app-sidebar is nested within the Angular component layout shown below: <div fxlayout="row" fxFill> <app-sidebar fxLayout="column" fxFlex="10%"></app-sidebar> <div ...

Experimenting with Typescript, conducting API call tests within Redux actions, mimicking classes with Enzyme, and using Jest

I am facing an issue where I need to mock a class called Api that is utilized within my redux actions. This class is responsible for making axios get and post requests which also need to be mocked. Despite following tutorials on how to mock axios and class ...

Issues with user-generated input not properly functioning within a react form hook

After following the example provided here, I created a custom input component: Input.tsx import React from "react"; export default function Input({label, name, onChange, onBlur, ref}:any) { return ( <> <label htmlF ...

Angular - CSS Grid - Positioning columns based on their index values

My goal is to create a CSS grid with 4 columns and infinite rows. Specifically, I want the text-align property on the first column to be 'start', the middle two columns to be 'center', and the last column to be 'end'. The cont ...

The Angular subscribe value is consistently assigned as -1, just before it receives the actual assigned value

Upon completion of the .subscribe, I am attempting to trigger an event as the subsequent code relies on the result. checkIfBordereauExists(id: string) { return this._BourdereauService.get_one(id).subscribe( data = > { if (data.i ...

Angular CLI simplifies the process of implementing internationalization (i18n) for Angular

After diving into the Angular documentation on i18n and using the ng tool xi18n, I am truly impressed by its capabilities. However, there is one part that has me stumped. According to the documentation, when internationalizing with the AOT compiler, you ...

The Angular component template fails to reflect the current value received from the observable

I am facing an issue with a component that updates its state from a service observable: import {Component} from '@angular/core'; import {SessionTimeoutService} from "./session-timeout/session-timeout.service"; import {Observable} from & ...

What is the process of adding an m4v video to a create-next-app using typescript?

I encountered an issue with the following error: ./components/Hero.tsx:2:0 Module not found: Can't resolve '../media/HeroVideo1-Red-Compressed.m4v' 1 | import React, { useState } from 'react'; > 2 | import Video from '../ ...

The final value of a loop is consistently returned each time

Creating a loop to generate objects. Action.ts public campaing:any = { 'id': '', 'campaing_code': '', 'campaing_type': '', 'start_date': this.currentDate, 'end ...

Receiving the error notification from a 400 Bad Request

I'm having trouble showing the errors returned from an API on my Sign up form when a user submits invalid data. You can check out the error response in the console here: console ss This is my approach in RegisterComponent.ts: onSubmit() { this.u ...

Enhance the glowing spinner in a react typescript application

Recently, I transformed an html/css spinner into a react component. However, it seems to be slowing down other client-side processes significantly. You can see the original design on the left and the spinning version on the right in the image below: This ...

What is the correct version compatibility matrix for Expo, NPM, Node, React Native, and TypeScript?

Currently, I am in the process of setting up React Native with TypeScript. Here are the steps I followed: npx react-native init MyApp --template react-native-template-typescript I made sure to install TypeScript as well: npm install -g typescript ' ...

The issue I'm facing with my webpack-build is the exclusive appearance of the "error" that

Hey everyone! I'm currently facing an issue with importing a module called _module_name_ into my React project, specifically a TypeScript project named react-app. The module was actually developed by me and it's published on npm. When trying to i ...

Encountering a Typescript TypeError in es2022 that is not present in es2021

I'm attempting to switch the target property in the tsconfig.json file from es2015 to es2022, but I am encountering an error while running tests that seem to only use tsc without babel: Chrome Headless 110.0.5481.177 (Mac OS 10.15.7) TypeError: Can ...

How to trigger a component programmatically in Angular 6

Whenever I hover over an <li> tag, I want to trigger a function that will execute a detailed component. findId(id:number){ console.log(id) } While this function is executing, it should send the id to the following component: export class ...

Waiting for variable to become false using Angular 7 Observable

The observable below highlights the authentication process: import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { CookieService } from 'ngx-cookie-service'; import { Observabl ...

Retrieve data from a URL using Angular 6's HTTP POST method

UPDATE: Replaced res.json(data) with res.send(data) I am currently working on a web application using Angular 6 and NodeJS. My goal is to download a file through an HTTP POST request. The process involves sending a request to the server by calling a func ...

Tips for developing a strongly-typed generic function that works seamlessly with redux slices and their corresponding actions

Currently, I am working with @reduxjs/toolkit and aiming to develop a function that can easily create a slice with default reducers. Although my current implementation is functional, it lacks strong typing. Is there a way to design a function in such a man ...

Combining TypeScript and JavaScript for efficient mixins

I came across an article on MDN discussing the usage and creation of mix-ins (link). Intrigued, I decided to try implementing it in TypeScript: type Constructor = new (...args: any) => any; function nameMixin(Base: Constructor) { return class extends ...