Using TypeScript to Calculate Hours and Minutes Between Two Time Values

In this scenario, the start time is 11:30 and the end time is 13:00.

The expected output should be 1:30.

Is there a TypeScript code snippet that can achieve this result?

Answer №1

If you're feeling unsure about the task at hand, consider using this sample code for guidance:

const startTime = '11.30'; 
const endTime = '13.0';

let [startHour, startMin] = startTime.split('.')
let [endHour, endMin] = endTime.split('.')

let startDate = new Date(0, 0, 0, startHour, startMin, 0);
let endDate = new Date(0, 0, 0, endHour, endMin, 0);

let timeDifference = endDate.getTime() - startDate.getTime();
let hours = Math.floor(timeDifference / 1000 / 60 / 60);

timeDifference -= hours * 1000 * 60 * 60;
let minutes = Math.floor(timeDifference / 1000 / 60);

console.log(`The time difference is ${hours} hours and ${minutes} minutes`);

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

Is there a way to enhance a generic parameter using another generic parameter in TypeScript?

I am struggling with repetitive code that involves a type with minor variations: import { ComponentPropsWithRef, ElementType } from "react"; interface PackshotPropsBase { a: string } interface PackshotPropsWeb { b: string } export type Ele ...

Setting up TypeScript to function with Webpack's resolve.modules

Imagine having a webpack configuration that looks like this: resolve: { extensions: ['.ts', '.tsx', '.js', '.jsx', '.json'], modules: ['my_modules', 'node_modules'], }, You have a ...

What is the method for combining a number with a variable designation?

Hey there, I'm having some trouble changing the variable name in a loop. I attempted to use a for loop with "stop" + i, but it didn't quite work out as I had hoped. Any assistance would be greatly appreciated! ...

Having issues with unexpected token in Typescript while using "as HTMLElement" type?

I recently started learning Typescript and I encountered an error while using the HTMLElement type in a forEach loop: ERROR in ./app/javascript/mount.jsx Module build failed (from ./node_modules/babel-loader/lib/index.js): SyntaxError: /Users/me/projects/m ...

What causes an error when the App is enclosed within a Provider component?

What is causing the error when wrapping the App in Provider? Are there any additional changes or additions needed? Error: "could not find react-redux context value; please ensure the component is wrapped in a @Provider@" import React from ' ...

How to bring in an interface in Angular 2

For my Meteor app using Angular 2, I am looking to create a custom data type like the one below: interface MyCustomType { index: number; value: string; } To use this custom type across multiple files, I attempted to create a separate file named "mycu ...

Exploring Angular2 Heroes Guide - Declaring Hero Properties with Nested Objects

Currently, I am diving into the Angular2 Tour of Heroes guide and striving to grasp the concept of services. So far, I've successfully implemented the basic tutorial, but as I attempt to add more complexity, my application crashes without clear reason ...

Instructions on invoking a function from another Material UI TypeScript component using React

In this scenario, we have two main components - the Drawer and the AppBar. The AppBar contains a menu button that is supposed to trigger an event opening the Drawer. However, implementing this functionality has proven challenging. I attempted to use the li ...

Vue.js Element UI dialog box

Is there a method to customize the close button in el-dialog and replace it with my own design? For instance, can I change the default close button located at the top left corner of the dialog? <el-dialog title="Tips" :visible.sync=" ...

Having trouble locating the export in the TypeScript module

Having a situation where there is a file with an exported object: let btypes:{[key:string]:any} = { "key1":val, //... } export {btypes} I even attempted to use export default btypes Upon importing it using: import {btypes} from "../types& ...

Connect your Angular2 app to the global node modules folder using this link

Is there a way to set up a centralized Node modules folder on the C disk instead of having it locally within the app directory? This would be more convenient as Angular2 CLI tends to install over 125mb of Node modules in the local folder. In our TypeScrip ...

Leverage glob patterns within TypeScript declaration files

Utilizing the file-loader webpack plugin allows for the conversion of media imports into their URLs. For example, in import src from './image.png', the variable src is treated as a string. To inform TypeScript about this behavior, one can create ...

Error message while attempting to update devextreme-datagrid: "Received HTTP failure response for an unknown URL: 0 Unknown Error"

Need help with updating the devextreme-datagrid. Can anyone assist? lineController.js router.put("/:id", (req, res) => { if (!ObjectId.isValid(req.params.id)) return res.status(400).send(`No record with given id : ${req.params.id}`); ...

Issues arise as a result of conflicts between the dependencies of @ionic/angular, Angular 13, typescript,

Current Environment Details: ionic info Ionic: Ionic CLI : 6.18.1 (/usr/local/lib/node_modules/@ionic/cli) Ionic Framework : @ionic/angular 5.8.5 @angular-devkit/build-angular : 13.0.2 @angular-devkit/schemat ...

I implemented progress bars in Angular 2 that have changing maximum values. The service updates the maximum value for each bar dynamically. Currently, the progress bars are functioning at 100% capacity

this.games=[ {"val":50, "name":"Articlescontributed","max":35}, {"val":30 ,"name":"Articlesrated", "max":999}, {"val":20, "name":"Views", "max":35}, {"val":30, "name":"Ratings", "max":35}, {"val":20, "name":"Follower", "max":200}, { ...

Dealing with Cross-Origin Resource Sharing problem in a React, TypeScript, Vite application with my .NET backend

I'm encountering a CORS issue when trying to make a Request using Fetch and Axios in my application hosted on the IIS Server. Here are my Server API settings: <httpProtocol> <customHeaders> <add name="Access-Control-Allow-O ...

What causes the Angular child component (navbar) to no longer refresh the view after a route change?

Hello everyone, I'm excited to ask my first question here. Currently, I am working on developing a social network using the MEAN stack and socket.io. One of the challenges I am facing is displaying the number of unread notifications and messages next ...

An issue has occurred: function() is not a valid function

Issue: core.mjs:10132 ERROR TypeError: block.getDepartment is not a function at FirebaseService.mapDatabaseToBlock (firebase.service.ts:54:30) at firebase.service.ts:45:60 at Array.map (<anonymous>) at firebase.service.ts:45:42 at ...

Whenever I update the values in my input using the ngModel attribute, all of my arrays stored in an object also get updated

I am currently working with a table on the frontend. <table class="table table-hover"> <thead> <tr> <th> Account Entry Number </th> <th> ...

Utilizing a library that solely enhances the functionality of the Array object

I have a library with type definitions structured like this: declare global { interface Array<T> { addRange<T>(elements: T[]): void; aggregate<U>(accumulator: (accum: U, value?: T, index?: number, list?: T[]) => an ...