From cb111b0d8be5383d5693b60073ef07c7a5b01ea6 Mon Sep 17 00:00:00 2001 From: Michael Olayemi Date: Mon, 14 Aug 2023 18:03:59 +0100 Subject: [PATCH] Conversion From 12 Hours Time to 24 Hours Time in Java (#14580) --- .../TimeConversionUnitTest.java | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 core-java-modules/core-java-datetime-conversion/src/test/java/com/baeldung/twelvehourstotwentyhours/TimeConversionUnitTest.java diff --git a/core-java-modules/core-java-datetime-conversion/src/test/java/com/baeldung/twelvehourstotwentyhours/TimeConversionUnitTest.java b/core-java-modules/core-java-datetime-conversion/src/test/java/com/baeldung/twelvehourstotwentyhours/TimeConversionUnitTest.java new file mode 100644 index 0000000000..e82af6dd19 --- /dev/null +++ b/core-java-modules/core-java-datetime-conversion/src/test/java/com/baeldung/twelvehourstotwentyhours/TimeConversionUnitTest.java @@ -0,0 +1,30 @@ +package com.baeldung.twelvehourstotwentyhours; + +import static org.junit.jupiter.api.Assertions.*; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.time.LocalTime; +import java.time.format.DateTimeFormatter; +import java.util.Date; +import java.util.Locale; +import org.junit.jupiter.api.Test; + +public class TimeConversionUnitTest { + + @Test + public void givenTimeInTwelveHours_whenConvertingToTwentyHours_thenConverted() throws ParseException { + SimpleDateFormat displayFormat = new SimpleDateFormat("HH:mm"); + SimpleDateFormat parseFormat = new SimpleDateFormat("hh:mm a"); + Date date = parseFormat.parse("06:00 PM"); + assertEquals("18:00", displayFormat.format(date)); + } + + @Test + public void givenTimeInTwelveHours_whenConvertingToTwentyHoursWithDateTimeFormatter_thenConverted() throws ParseException { + String time = LocalTime.parse("06:00 PM", DateTimeFormatter.ofPattern("hh:mm a", Locale.US)) + .format(DateTimeFormatter.ofPattern("HH:mm")); + assertEquals("18:00", time); + } + +}