Skip to content

Commit 2a1a280

Browse files
committed
add: added converter with example
1 parent 91197f3 commit 2a1a280

File tree

1 file changed

+91
-0
lines changed

1 file changed

+91
-0
lines changed

Conversions/ConvertTime.php

Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
<?php
2+
3+
/**
4+
* Converts a value from one time unit to another.
5+
*
6+
* @author Arafat Hossain
7+
* @link https://github.com/arafat-web
8+
* @param float $value The value to convert.
9+
* @param string $fromUnit The current unit of the value.
10+
* @param string $toUnit The target unit to convert the value to.
11+
* @throws InvalidArgumentException If the fromUnit or toUnit is invalid.
12+
* @return float The converted value, rounded to two decimal places.
13+
*/
14+
function convertTime(float $value, string $fromUnit, string $toUnit): float
15+
{
16+
$conversionFactors = [
17+
'seconds' => [
18+
'minutes' => 1 / 60,
19+
'hours' => 1 / 3600,
20+
'days' => 1 / 86400,
21+
'weeks' => 1 / 604800,
22+
'months' => 1 / 2592000,
23+
'years' => 1 / 31536000
24+
],
25+
'minutes' => [
26+
'seconds' => 60,
27+
'hours' => 1 / 60,
28+
'days' => 1 / 1440,
29+
'weeks' => 1 / 10080,
30+
'months' => 1 / 43200,
31+
'years' => 1 / 525600
32+
],
33+
'hours' => [
34+
'seconds' => 3600,
35+
'minutes' => 60,
36+
'days' => 1 / 24,
37+
'weeks' => 1 / 168,
38+
'months' => 1 / 720,
39+
'years' => 1 / 8760
40+
],
41+
'days' => [
42+
'seconds' => 86400,
43+
'minutes' => 1440,
44+
'hours' => 24,
45+
'weeks' => 1 / 7,
46+
'months' => 1 / 30.4,
47+
'years' => 1 / 365.25
48+
],
49+
'weeks' => [
50+
'seconds' => 604800,
51+
'minutes' => 10080,
52+
'hours' => 168,
53+
'days' => 7,
54+
'months' => 1 / 4.3,
55+
'years' => 1 / 52.17
56+
],
57+
'months' => [
58+
'seconds' => 2592000,
59+
'minutes' => 43200,
60+
'hours' => 720,
61+
'days' => 30.4,
62+
'weeks' => 4.3,
63+
'years' => 1 / 12
64+
],
65+
'years' => [
66+
'seconds' => 31536000,
67+
'minutes' => 525600,
68+
'hours' => 8760,
69+
'days' => 365.25,
70+
'weeks' => 52.17,
71+
'months' => 12
72+
]
73+
];
74+
75+
if (!isset($conversionFactors[$fromUnit], $conversionFactors[$fromUnit][$toUnit])) {
76+
throw new InvalidArgumentException("Invalid time unit(s) specified: $fromUnit to $toUnit.");
77+
}
78+
79+
$conversionFactor = $conversionFactors[$fromUnit][$toUnit];
80+
$result = $value * $conversionFactor;
81+
82+
return round($result, 2);
83+
}
84+
85+
// Example usage
86+
try {
87+
$timeResult = convertTime(120, 'minutes', 'seconds');
88+
echo "120 minutes = $timeResult seconds\n";
89+
} catch (InvalidArgumentException $e) {
90+
echo "Error: " . $e->getMessage() . "\n";
91+
}

0 commit comments

Comments
 (0)