File tree Expand file tree Collapse file tree
core-java-modules/core-java-datetime-conversion-2/src
main/java/com/baeldung/convertdateandzoneddatetime
test/java/com/baeldung/convertdateandzoneddatetime Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ package com .baeldung .convertdateandzoneddatetime ;
2+
3+ import java .time .ZoneId ;
4+ import java .time .ZonedDateTime ;
5+ import java .util .Date ;
6+
7+ public class DateAndZonedDateTimeConverter {
8+
9+ public static Date convertToDate (ZonedDateTime zonedDateTime ) {
10+ return Date .from (zonedDateTime .toInstant ());
11+ }
12+
13+ public static ZonedDateTime convertToZonedDateTime (Date date , ZoneId zone ) {
14+ return date .toInstant ().atZone (zone );
15+ }
16+
17+ }
Original file line number Diff line number Diff line change 1+ package com .baeldung .convertdateandzoneddatetime ;
2+
3+ import org .junit .jupiter .api .Test ;
4+
5+ import java .time .ZoneId ;
6+ import java .time .ZonedDateTime ;
7+ import java .util .Date ;
8+
9+ import static org .junit .jupiter .api .Assertions .assertEquals ;
10+
11+ public class DateAndZonedDateTimeConverterUnitTest {
12+
13+ @ Test
14+ public void givenZonedDateTime_whenConvertToDate_thenCorrect () {
15+ ZonedDateTime zdt = ZonedDateTime .now (ZoneId .of ("UTC" ));
16+ Date date = DateAndZonedDateTimeConverter .convertToDate (zdt );
17+ assertEquals (Date .from (zdt .toInstant ()), date );
18+ }
19+
20+ @ Test
21+ public void givenDate_whenConvertToZonedDateTime_thenCorrect () {
22+ Date date = new Date ();
23+ ZoneId zoneId = ZoneId .of ("UTC" );
24+ ZonedDateTime zdt = DateAndZonedDateTimeConverter .convertToZonedDateTime (date , zoneId );
25+ assertEquals (date .toInstant ().atZone (zoneId ), zdt );
26+ }
27+
28+ }
You can’t perform that action at this time.
0 commit comments