[BAEL-7767] Convert-between-ZonedDateTime-and-Date (#16490)
This commit is contained in:
parent
df6b36303a
commit
211df8196f
|
@ -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);
|
||||
}
|
||||
|
||||
}
|
|
@ -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);
|
||||
}
|
||||
|
||||
}
|
Loading…
Reference in New Issue