Skip to content

Commit

Permalink
fix: time formatter bug
Browse files Browse the repository at this point in the history
  • Loading branch information
SuhasDissa committed Apr 27, 2024
1 parent d68da12 commit 2afeeb7
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 1 deletion.
8 changes: 7 additions & 1 deletion app/src/main/java/com/bnyro/clock/util/TimeHelper.kt
Original file line number Diff line number Diff line change
Expand Up @@ -61,12 +61,18 @@ object TimeHelper {

}

/**
* Converts milliseconds to a formatted time string.
*
* @param millis The milliseconds since midnight.
* @return The formatted time string.
*/
fun millisToFormatted(millis: Long): String {
val timeFormatter = DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT)
val localTime = LocalTime.of(
millis.div(1000 * 60 * 60).toInt(),
millis.div(1000 * 60).mod(60),
millis.mod(1000)
millis.div(1000).mod(60)
)
return timeFormatter.format(localTime)
}
Expand Down
35 changes: 35 additions & 0 deletions app/src/test/java/com/bnyro/clock/TimeFormatterTest.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package com.bnyro.clock

import com.bnyro.clock.util.TimeHelper.millisToFormatted
import org.junit.Assert.assertEquals
import org.junit.Test
import java.time.LocalTime
import java.time.format.DateTimeFormatter
import java.time.format.FormatStyle

class TimeFormatterTest {

@Test
fun millisToFormatted_convertsMillisToFormattedTime() {
// Test case 1: Midnight
val millis1 = 0L
val formattedTime1 = millisToFormatted(millis1)
val expectedTime1 =
LocalTime.MIDNIGHT.format(DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT))
assertEquals(expectedTime1, formattedTime1)

// Test case 2: Afternoon time
val millis2 = 12 * 60 * 60 * 1000L // 12:00:00 PM
val formattedTime2 = millisToFormatted(millis2)
val expectedTime2 =
LocalTime.NOON.format(DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT))
assertEquals(expectedTime2, formattedTime2)

// Test case 3: Time with milliseconds
val millis3 = ((10 * 60 + 33) * 60 + 54) * 1000L + 567L // 10:33:54.567 AM
val formattedTime3 = millisToFormatted(millis3)
val expectedTime3 = LocalTime.of(10, 33, 54, 567_000_000)
.format(DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT))
assertEquals(expectedTime3, formattedTime3)
}
}

0 comments on commit 2afeeb7

Please sign in to comment.