From c519d2be47c15ecad61d3f9e21b3e198c565d352 Mon Sep 17 00:00:00 2001 From: michaelin007 Date: Fri, 24 Nov 2023 09:35:01 +0000 Subject: [PATCH] https://jira.baeldung.com/browse/BAEL-7268 --- .../baeldung/unixtime/UnixTimeUnitTest.java | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 core-java-modules/core-java-8-datetime-2/src/test/java/com/baeldung/unixtime/UnixTimeUnitTest.java diff --git a/core-java-modules/core-java-8-datetime-2/src/test/java/com/baeldung/unixtime/UnixTimeUnitTest.java b/core-java-modules/core-java-8-datetime-2/src/test/java/com/baeldung/unixtime/UnixTimeUnitTest.java new file mode 100644 index 0000000000..d1518ceef5 --- /dev/null +++ b/core-java-modules/core-java-8-datetime-2/src/test/java/com/baeldung/unixtime/UnixTimeUnitTest.java @@ -0,0 +1,50 @@ +package com.baeldung.unixtime; + + +import static org.junit.Assert.assertEquals; + +import java.time.Instant; +import java.util.Date; + +import org.joda.time.DateTime; +import org.joda.time.DateTimeZone; +import org.junit.jupiter.api.Test; + +public class UnixTimeUnitTest { + + @Test + public void givenCurrentTimeUsingDateApi_whenConvertedToUnixTime_thenConsistent() { + long marginOfError = 1L; + Date date = new Date(); + long longTime = date.getTime() / 1000L; + + for (int i = 0; i < 10; i++) { + long unixTime = System.currentTimeMillis() / 1000L; + assertEquals(longTime, unixTime, marginOfError); + } + } + + @Test + public void givenCurrentTimeUsingInstantNow_whenConvertedToUnixTime_thenConsistent() { + long marginOfError = 1L; + long longTime = Instant.now().getEpochSecond(); + + for (int i = 0; i < 10; i++) { + long unixTime = System.currentTimeMillis() / 1000L; + assertEquals(longTime, unixTime, marginOfError); + } + } + + @Test + public void givenCurrentTimeUsingJodaTime_whenConvertedToUnixTime_thenConsistent() { + long marginOfError = 1L; + DateTime dateTime = DateTime.now(DateTimeZone.UTC); + long longTime = dateTime.getMillis() / 1000L; + + for (int i = 0; i < 10; i++) { + long unixTime = System.currentTimeMillis() / 1000L; + assertEquals(longTime, unixTime, marginOfError); + } + } + +}