[BAEL-7767] Convert-between-ZonedDateTime-and-Date (#16490)

This commit is contained in:
vunamtien 2024-04-25 23:01:54 +07:00 committed by GitHub
parent df6b36303a
commit 211df8196f
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 45 additions and 0 deletions

View File

@ -0,0 +1,17 @@
package com.baeldung.convertdateandzoneddatetime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Date;
public class DateAndZonedDateTimeConverter {
public static Date convertToDate(ZonedDateTime zonedDateTime) {
return Date.from(zonedDateTime.toInstant());
}
public static ZonedDateTime convertToZonedDateTime(Date date, ZoneId zone) {
return date.toInstant().atZone(zone);
}
}

View File

@ -0,0 +1,28 @@
package com.baeldung.convertdateandzoneddatetime;
import org.junit.jupiter.api.Test;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Date;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class DateAndZonedDateTimeConverterUnitTest {
@Test
public void givenZonedDateTime_whenConvertToDate_thenCorrect() {
ZonedDateTime zdt = ZonedDateTime.now(ZoneId.of("UTC"));
Date date = DateAndZonedDateTimeConverter.convertToDate(zdt);
assertEquals(Date.from(zdt.toInstant()), date);
}
@Test
public void givenDate_whenConvertToZonedDateTime_thenCorrect() {
Date date = new Date();
ZoneId zoneId = ZoneId.of("UTC");
ZonedDateTime zdt = DateAndZonedDateTimeConverter.convertToZonedDateTime(date, zoneId);
assertEquals(date.toInstant().atZone(zoneId), zdt);
}
}