From milliseconds to hours: a straightforward conversion

Given a start date, time and end date, time, I am trying to calculate the total travel duration. The output is in milliseconds and needs to be converted into hours format. Despite attempting some solutions shared here, I haven't been successful.

<md-cell *mdCellDef="let row"> {{row?.duration | formatDuration}} </md-cell>

Here is the related ts file:

  export class StoppageComponent implements OnInit {

  constructor() {
  }

  ngOnInit() {
  }


      filter('formatDuration', function () {
        return function (input) {
            var totalHours, totalMinutes, totalSeconds, hours, minutes, seconds, result='';

            totalSeconds = input / 1000;
            totalMinutes = totalSeconds / 60;
            totalHours = totalMinutes / 60;

            seconds = Math.floor(totalSeconds) % 60;
            minutes = Math.floor(totalMinutes) % 60;
            hours = Math.floor(totalHours) % 60;

            if (hours !== 0) {
                result += hours+':';

                if (minutes.toString().length == 1) {
                    minutes = '0'+minutes;
                }
            }

            result += minutes+':';

            if (seconds.toString().length == 1) {
                seconds = '0'+seconds;
            }

            result += seconds;

            return result;
        };
      });
    }

I suspect that the issue lies within the ts file code since I am relatively new to Angular.

Is there a way to directly convert this using a pipe without relying on functions?

Answer №1

After reviewing other answers and finding them to be quite complicated, I managed to come up with a solution on my own.

Here is the HTML code:

<md-cell *mdCellDef="let row"> {{getFormathours(row?.duration)}} </md-cell>

And here is the TypeScript code:

getFormathours(input) {
    var totalHours, totalMinutes, totalSeconds, hours, minutes, seconds, result='';
    totalSeconds = input / 1000;
    totalMinutes = totalSeconds / 60;
    totalHours = totalMinutes / 60;

    seconds = Math.floor(totalSeconds) % 60;
    minutes = Math.floor(totalMinutes) % 60;
    hours = Math.floor(totalHours) % 60;

    console.log (hours + ' : '  + minutes + ' : ' + seconds);
    if (hours !== 0) {
        result += hours+' hr:';

        if (minutes.toString().length == 1) {
            minutes = '0'+minutes;
        }
    }

    result += minutes+' min';

      if (seconds.toString().length == 1) {
          seconds = '0'+seconds;
      }

      result += seconds;

    return result;
}

This solution provides exactly what I needed and offers a clearer explanation tailored to my question. I would like to thank those who provided other answers for their effort as well.

Answer №2

Don't waste time trying to come up with something new. Utilize Date objects for calculating duration.

If you have two date objects as inputs,

  • Calculate the difference between them in milliseconds, which is already done.
  • Create a new date object and remove the time value from it.
  • Assign the time difference to this new date object to extract the necessary values. Simply invoke the function to display the values in your desired format.

function getTravelTime(date1, date2) {
  var diff = +date2 - +date1;
  var today = new Date();
  today.setHours(0,0,0,0);
  var arrival = new Date(+today + diff);
  var duration = ['getFullYear', 'getMonth', 'getDate', 'getHours', 'getMinutes', 'getSeconds'].reduce(function(p,c,i,a){
    var value = arrival[c]() - today[c]();
    if(value) {
      p += value;
      p += ((c === 'getFullYear') ? ' Year' : c.replace('get', ' ')) + ' '
    }
    return p;
  }, '');
  console.log(duration);
}

function doubleDigits(str){
  return ('00' + str).slice(-2)
}

getTravelTime(new Date(2017, 10, 5, 5), new Date(2017, 10, 5, 15, 23));
getTravelTime(new Date(2017, 10, 5, 5), new Date(2017, 10, 6, 15, 23, 30));

Answer №3

To ensure accuracy and avoid errors, I recommend utilizing the moment library instead of Date. You can find more information at https://momentjs.com/docs/

var t1 = moment('2017/10/5 15:23');
var t2 = moment('2017/10/5 15:23');

var differenceMinutes = t1.diff(t2, 'minutes');
var differenceMilliseconds = t1.diff(t2, 'minutes');

Opting for well-known and reliable libraries can improve efficiency. For Angular templates, you can use:

https://github.com/urish/angular2-moment

Here's an example:

{{startDate | amDifference: endDate :'' }}

Answer №4

Feel free to utilize this code as is

export class StoppageComponent implements OnInit {

constructor() {
 }

ngOnInit() {
}


filter('formatDuration', function () {
    return function (input) {
        var result = new Date(input);
var n = (d.getDate().toString()) +'/'+ (d.getMonth().toString())+'/' +(d.getFullYear().toString()) + '  '+ (d.getHours().toString()) +':'+ (d.getHours().toString()) +':'+ (d.getSeconds().toString());

        return result;
    };
  });
}

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

Step-by-step guide on how to change the appearance of a <DIV> using data from a database (JSON

After retrieving data from a database as a JSON file, I have written code to loop through an item (portOn) and determine if certain ports are present in the array. If a port is found in the array, its corresponding variable is set to true. var portG01,port ...

Identify modifications in the input and at the same time update another input

I currently have two input text boxes. My goal is to synchronize the content of the second input box whenever the first input box is changed. I attempted to achieve this using this code snippet. However, I encountered an issue where the synchronization on ...

Open $_POST in a new tab that has been edited for your convenience

<form method="post" target="_blank" action="battle.php" onsubmit="window.open('battle.php','','width=700,height=500,toolbar=0,menubar=0,location=0,status=0,scrollbars=0,resizable=0,left=30,top=0');" > < ...

Revamp your outdated components with 15 modern Angular Material styles

After upgrading to Angular 15, I am aiming to utilize legacy components first before proceeding with a continuous migration process. However, the legacy components lack certain styles and appear incorrectly formatted. To facilitate the migration from Angu ...

Teaching you how to incorporate empty spaces and punctuation within JOI

How can I modify Joi to permit spaces/whitespaces in a title field within a form? Scheduled to work with Jude tomorrow. I want to allow entries like: Morningwalk Currently, only the second example is passing validation. Below is my existing Joi val ...

What is the method for assigning 'selective-input' to a form field in Angular?

I am using Angular and have a form input field that is meant to be filled with numbers only. Is there a way to prevent any characters other than numbers from being entered into the form? I want the form to behave as if only integer keys on the keyboard ar ...

Unable to modify the value of a key within an object using TypeScript

I'm struggling to update the value of a key within an object using TypeScript. Here's an overview of the types I'm working with: export enum BAR_TYPES { apple = "apple", banana = "banana" } export type BarTypes = ...

Just systems that have been positively identified

Greetings! I am currently in the process of creating a small online stock management system using PHP. However, my goal is to restrict access to this web app to only certain systems that I designated. I want to ensure that only the systems under my contro ...

Event handling in Angular when the window is resized

I am looking to execute certain tasks based on the window resizing event, both when it loads and dynamically during interaction. My current DOM structure is as follows: <div id="Harbour"> <div id="Port" (window:resize)=&qu ...

Use ng-click to enable specific actions only on the element in which it is placed

Using ng-repeat, I have created a series of elements... <div class="form-block" ng-repeat="form in formblock | filter:dateFilter"> <div ng-click="showResults()" ng-if="repeat == true" class="drop">{{ form.form_name }} <span class="care ...

Synchronizing timers among different elements

Just a little context: I'm diving into the world of React and currently working on a small app using next.js (with a template from a tutorial I followed some time ago). Lately, I've encountered a challenge where I need to synchronize a timer betw ...

Developing a personalized validation function using Typescript for the expressValidator class - parameter is assumed to have a type of 'any'

I'm seeking to develop a unique validation function for express-validator in typescript by extending the 'body' object. After reviewing the helpful resource page, I came across this code snippet: import { ExpressValidator } from 'expre ...

Tips on incorporating a hyperlink into an object imported through GLTF loader

Is there a way to include a hyperlink in the object loaded using gltf loader with the given code snippet below? var loader = new THREE.GLTFLoader(); var mesh; loader.load('globe.glb', function(gltf){ console.log(gltf); me ...

Encountering an unknown error with lite server when running npm start

A few weeks back, I was working on an Angular2 project and left it as is in the cloud. However, now when I try to run the project, I encounter an error right from the start. I suspect that the issue lies with lite-server, even though I have updated the no ...

Executing a SQL query using a JavaScript variable as a parameter

I am currently working on a website form that includes a select menu populated with data from an SQL table using a loop. The form is being displayed using JavaScript scripts, which are functioning perfectly. However, I am facing an issue in the final step ...

Tips for retrieving a flag when there is a preexisting record within an association in Sequelize

I am working with a model A that has a 1:N association with a model B. My objective is to retrieve all records from A and determine whether there is at least one associated record from B (true) or not (false). The relationship setup: ModelA.hasMany(ModelB ...

deleting a aircraft upon the addition of another in three.js

I am striving to implement a button that toggles between different terrain-generating functions and removes the previous terrain. The current issue I am facing is that the planes stack on top of each other. You can see an image of the problem here. There ...

The Angular test spy is failing to be invoked

Having trouble setting up my Angular test correctly. The issue seems to be with my spy not functioning as expected. I'm new to Angular and still learning how to write tests. This is for my first Angular app using the latest version of CLI 7.x, which i ...

How can I optimize my .find query for a MongoDB GET request to achieve maximum performance?

I'm struggling to figure out how to retrieve only the last item stored in my database using a GET request. While I can successfully get the desired output in the mongo shell (as shown below), I haven't been able to replicate it in my GET route qu ...

Creating a corner ribbon for a Material UI Card: A step-by-step guide

Can anyone provide pointers on incorporating a corner ribbon to a Material-UI card? Currently, I am utilizing makeStyles for styling from Material UI. ...