Skip to content

Commit 506b6d1

Browse files
DEV: Implementing Time Conversion Algorithm (#6556)
* Added-time-converter-algorithm * Updated-java-docs * Fixed-formatting-issues * Enhanced-unit-tests * Fixed-failing-check-style --------- Co-authored-by: Deniz Altunkapan <93663085+DenizAltunkapan@users.noreply.github.com>
1 parent 977c982 commit 506b6d1

File tree

2 files changed

+166
-0
lines changed

2 files changed

+166
-0
lines changed
Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
package com.thealgorithms.conversions;
2+
3+
import java.util.Locale;
4+
import java.util.Map;
5+
6+
/**
7+
* A utility class to convert between different units of time.
8+
*
9+
* <p>This class supports conversions between the following units:
10+
* <ul>
11+
* <li>seconds</li>
12+
* <li>minutes</li>
13+
* <li>hours</li>
14+
* <li>days</li>
15+
* <li>weeks</li>
16+
* <li>months (approximated as 30.44 days)</li>
17+
* <li>years (approximated as 365.25 days)</li>
18+
* </ul>
19+
*
20+
* <p>The conversion is based on predefined constants in seconds.
21+
* Results are rounded to three decimal places for consistency.
22+
*
23+
* <p>This class is final and cannot be instantiated.
24+
*
25+
* @see <a href="https://en.wikipedia.org/wiki/Unit_of_time">Wikipedia: Unit of time</a>
26+
*/
27+
public final class TimeConverter {
28+
29+
private TimeConverter() {
30+
// Prevent instantiation
31+
}
32+
33+
/**
34+
* Supported time units with their equivalent in seconds.
35+
*/
36+
private enum TimeUnit {
37+
SECONDS(1.0),
38+
MINUTES(60.0),
39+
HOURS(3600.0),
40+
DAYS(86400.0),
41+
WEEKS(604800.0),
42+
MONTHS(2629800.0), // 30.44 days
43+
YEARS(31557600.0); // 365.25 days
44+
45+
private final double seconds;
46+
47+
TimeUnit(double seconds) {
48+
this.seconds = seconds;
49+
}
50+
51+
public double toSeconds(double value) {
52+
return value * seconds;
53+
}
54+
55+
public double fromSeconds(double secondsValue) {
56+
return secondsValue / seconds;
57+
}
58+
}
59+
60+
private static final Map<String, TimeUnit> UNIT_LOOKUP
61+
= Map.ofEntries(Map.entry("seconds", TimeUnit.SECONDS), Map.entry("minutes", TimeUnit.MINUTES), Map.entry("hours", TimeUnit.HOURS), Map.entry("days", TimeUnit.DAYS), Map.entry("weeks", TimeUnit.WEEKS), Map.entry("months", TimeUnit.MONTHS), Map.entry("years", TimeUnit.YEARS));
62+
63+
/**
64+
* Converts a time value from one unit to another.
65+
*
66+
* @param timeValue the numeric value of time to convert; must be non-negative
67+
* @param unitFrom the unit of the input value (e.g., "minutes", "hours")
68+
* @param unitTo the unit to convert into (e.g., "seconds", "days")
69+
* @return the converted value in the target unit, rounded to three decimals
70+
* @throws IllegalArgumentException if {@code timeValue} is negative
71+
* @throws IllegalArgumentException if either {@code unitFrom} or {@code unitTo} is not supported
72+
*/
73+
public static double convertTime(double timeValue, String unitFrom, String unitTo) {
74+
if (timeValue < 0) {
75+
throw new IllegalArgumentException("timeValue must be a non-negative number.");
76+
}
77+
78+
TimeUnit from = resolveUnit(unitFrom);
79+
TimeUnit to = resolveUnit(unitTo);
80+
81+
double secondsValue = from.toSeconds(timeValue);
82+
double converted = to.fromSeconds(secondsValue);
83+
84+
return Math.round(converted * 1000.0) / 1000.0;
85+
}
86+
87+
private static TimeUnit resolveUnit(String unit) {
88+
if (unit == null) {
89+
throw new IllegalArgumentException("Unit cannot be null.");
90+
}
91+
TimeUnit resolved = UNIT_LOOKUP.get(unit.toLowerCase(Locale.ROOT));
92+
if (resolved == null) {
93+
throw new IllegalArgumentException("Invalid unit '" + unit + "'. Supported units are: " + UNIT_LOOKUP.keySet());
94+
}
95+
return resolved;
96+
}
97+
}
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
package com.thealgorithms.conversions;
2+
3+
import static org.junit.jupiter.api.Assertions.assertEquals;
4+
import static org.junit.jupiter.api.Assertions.assertThrows;
5+
6+
import java.util.stream.Stream;
7+
import org.junit.jupiter.api.DisplayName;
8+
import org.junit.jupiter.api.Test;
9+
import org.junit.jupiter.params.ParameterizedTest;
10+
import org.junit.jupiter.params.provider.CsvSource;
11+
import org.junit.jupiter.params.provider.MethodSource;
12+
13+
class TimeConverterTest {
14+
15+
@ParameterizedTest(name = "{0} {1} -> {2} {3}")
16+
@CsvSource({"60, seconds, minutes, 1", "120, seconds, minutes, 2", "2, minutes, seconds, 120", "2, hours, minutes, 120", "1, days, hours, 24", "1, weeks, days, 7", "1, months, days, 30.438", "1, years, days, 365.25", "3600, seconds, hours, 1", "86400, seconds, days, 1",
17+
"604800, seconds, weeks, 1", "31557600, seconds, years, 1"})
18+
void
19+
testValidConversions(double value, String from, String to, double expected) {
20+
assertEquals(expected, TimeConverter.convertTime(value, from, to));
21+
}
22+
23+
@Test
24+
@DisplayName("Zero conversion returns zero")
25+
void testZeroValue() {
26+
assertEquals(0.0, TimeConverter.convertTime(0, "seconds", "hours"));
27+
}
28+
29+
@Test
30+
@DisplayName("Same-unit conversion returns original value")
31+
void testSameUnitConversion() {
32+
assertEquals(123.456, TimeConverter.convertTime(123.456, "minutes", "minutes"));
33+
}
34+
35+
@Test
36+
@DisplayName("Negative value throws exception")
37+
void testNegativeValue() {
38+
assertThrows(IllegalArgumentException.class, () -> TimeConverter.convertTime(-5, "seconds", "minutes"));
39+
}
40+
41+
@ParameterizedTest
42+
@CsvSource({"lightyears, seconds", "minutes, centuries"})
43+
void testInvalidUnits(String from, String to) {
44+
assertThrows(IllegalArgumentException.class, () -> TimeConverter.convertTime(10, from, to));
45+
}
46+
47+
@Test
48+
@DisplayName("Null unit throws exception")
49+
void testNullUnit() {
50+
assertThrows(IllegalArgumentException.class, () -> TimeConverter.convertTime(10, null, "seconds"));
51+
52+
assertThrows(IllegalArgumentException.class, () -> TimeConverter.convertTime(10, "minutes", null));
53+
54+
assertThrows(IllegalArgumentException.class, () -> TimeConverter.convertTime(10, null, null));
55+
}
56+
57+
static Stream<org.junit.jupiter.params.provider.Arguments> roundTripCases() {
58+
return Stream.of(org.junit.jupiter.params.provider.Arguments.of(1.0, "hours", "minutes"), org.junit.jupiter.params.provider.Arguments.of(2.5, "days", "hours"), org.junit.jupiter.params.provider.Arguments.of(1000, "seconds", "minutes"));
59+
}
60+
61+
@ParameterizedTest
62+
@MethodSource("roundTripCases")
63+
@DisplayName("Round-trip conversion returns original value")
64+
void testRoundTripConversion(double value, String from, String to) {
65+
double converted = TimeConverter.convertTime(value, from, to);
66+
double roundTrip = TimeConverter.convertTime(converted, to, from);
67+
assertEquals(Math.round(value * 1000.0) / 1000.0, Math.round(roundTrip * 1000.0) / 1000.0, 0.05);
68+
}
69+
}

0 commit comments

Comments
 (0)