1import React, { FC } from 'react';
2import { toDuration } from '@grafana/data';
3
4export interface TimeProps {
5  timeInMs: number;
6  className?: string;
7  humanize?: boolean;
8}
9
10export const Time: FC<TimeProps> = ({ timeInMs, className, humanize }) => {
11  return <span className={`elapsed-time ${className}`}>{formatTime(timeInMs, humanize)}</span>;
12};
13
14const formatTime = (timeInMs: number, humanize = false): string => {
15  const inSeconds = timeInMs / 1000;
16
17  if (!humanize) {
18    return `${inSeconds.toFixed(1)}s`;
19  }
20
21  const duration = toDuration(inSeconds, 'seconds');
22  const hours = duration.hours();
23  const minutes = duration.minutes();
24  const seconds = duration.seconds();
25
26  if (hours) {
27    return `${hours}h ${minutes}m ${seconds}s`;
28  }
29
30  if (minutes) {
31    return `${minutes}m ${seconds}s`;
32  }
33
34  return `${seconds}s`;
35};
36