Merge pull request #8062 from martinvw/feature/BAEL-3315

[BAEL-3315] Added missing code snippets from the Java 8 Date/Time article
This commit is contained in:
Eric Martin
2019-10-23 20:45:39 -05:00
committed by GitHub
17 changed files with 330 additions and 43 deletions

View File

@@ -0,0 +1,21 @@
package com.baeldung.datetime;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.util.Locale;
public class UseDateTimeFormatter {
public String formatAsIsoDate(LocalDateTime localDateTime) {
return localDateTime.format(DateTimeFormatter.ISO_DATE);
}
public String formatCustom(LocalDateTime localDateTime, String pattern) {
return localDateTime.format(DateTimeFormatter.ofPattern(pattern));
}
public String formatWithStyleAndLocale(LocalDateTime localDateTime, FormatStyle formatStyle, Locale locale) {
return localDateTime.format(DateTimeFormatter.ofLocalizedDateTime(formatStyle)
.withLocale(locale));
}
}

View File

@@ -36,10 +36,15 @@ class UseLocalDate {
}
LocalDate getFirstDayOfMonth() {
LocalDate firstDayOfMonth = LocalDate.now().with(TemporalAdjusters.firstDayOfMonth());
LocalDate firstDayOfMonth = LocalDate.now()
.with(TemporalAdjusters.firstDayOfMonth());
return firstDayOfMonth;
}
boolean isLeapYear(LocalDate localDate) {
return localDate.isLeapYear();
}
LocalDateTime getStartOfDay(LocalDate localDate) {
LocalDateTime startofDay = localDate.atStartOfDay();
return startofDay;

View File

@@ -2,6 +2,7 @@ package com.baeldung.datetime;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneOffset;
import java.time.temporal.ChronoField;
public class UseLocalDateTime {
@@ -21,4 +22,7 @@ public class UseLocalDateTime {
return endOfDate;
}
LocalDateTime ofEpochSecond(int epochSecond, ZoneOffset zoneOffset) {
return LocalDateTime.ofEpochSecond(epochSecond, 0, zoneOffset);
}
}

View File

@@ -9,6 +9,10 @@ public class UseLocalTime {
return LocalTime.of(hour, min, seconds);
}
LocalTime getLocalTimeUsingFactoryOfMethod(int hour, int min) {
return LocalTime.of(hour, min);
}
LocalTime getLocalTimeUsingParseMethod(String timeRepresentation) {
return LocalTime.parse(timeRepresentation);
}

View File

@@ -0,0 +1,11 @@
package com.baeldung.datetime;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
public class UseOffsetDateTime {
public OffsetDateTime offsetOfLocalDateTimeAndOffset(LocalDateTime localDateTime, ZoneOffset offset) {
return OffsetDateTime.of(localDateTime, offset);
}
}

View File

@@ -12,31 +12,35 @@ class UseZonedDateTime {
return ZonedDateTime.of(localDateTime, zoneId);
}
ZonedDateTime getZonedDateTimeUsingParseMethod(String parsableString) {
return ZonedDateTime.parse(parsableString);
}
ZonedDateTime getStartOfDay(LocalDate localDate, ZoneId zone) {
ZonedDateTime startofDay = localDate.atStartOfDay()
ZonedDateTime startOfDay = localDate.atStartOfDay()
.atZone(zone);
return startofDay;
return startOfDay;
}
ZonedDateTime getStartOfDayShorthand(LocalDate localDate, ZoneId zone) {
ZonedDateTime startofDay = localDate.atStartOfDay(zone);
return startofDay;
ZonedDateTime startOfDay = localDate.atStartOfDay(zone);
return startOfDay;
}
ZonedDateTime getStartOfDayFromZonedDateTime(ZonedDateTime zonedDateTime) {
ZonedDateTime startofDay = zonedDateTime.toLocalDateTime()
ZonedDateTime startOfDay = zonedDateTime.toLocalDateTime()
.toLocalDate()
.atStartOfDay(zonedDateTime.getZone());
return startofDay;
return startOfDay;
}
ZonedDateTime getStartOfDayAtMinTime(ZonedDateTime zonedDateTime) {
ZonedDateTime startofDay = zonedDateTime.with(ChronoField.HOUR_OF_DAY, 0);
return startofDay;
ZonedDateTime startOfDay = zonedDateTime.with(ChronoField.HOUR_OF_DAY, 0);
return startOfDay;
}
ZonedDateTime getStartOfDayAtMidnightTime(ZonedDateTime zonedDateTime) {
ZonedDateTime startofDay = zonedDateTime.with(ChronoField.NANO_OF_DAY, 0);
return startofDay;
ZonedDateTime startOfDay = zonedDateTime.with(ChronoField.NANO_OF_DAY, 0);
return startOfDay;
}
}

View File

@@ -1,6 +1,6 @@
package com.baeldung.date;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import java.text.ParseException;
import java.text.SimpleDateFormat;
@@ -16,7 +16,7 @@ import java.util.Locale;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class DateDiffUnitTest {
@@ -38,7 +38,7 @@ public class DateDiffUnitTest {
LocalDate sixDaysBehind = now.minusDays(6);
Period period = Period.between(now, sixDaysBehind);
int diff = period.getDays();
int diff = Math.abs(period.getDays());
assertEquals(diff, 6);
}
@@ -68,7 +68,8 @@ public class DateDiffUnitTest {
public void givenTwoZonedDateTimesInJava8_whenDifferentiating_thenWeGetSix() {
LocalDateTime ldt = LocalDateTime.now();
ZonedDateTime now = ldt.atZone(ZoneId.of("America/Montreal"));
ZonedDateTime sixDaysBehind = now.withZoneSameInstant(ZoneId.of("Asia/Singapore")).minusDays(6);
ZonedDateTime sixDaysBehind = now.withZoneSameInstant(ZoneId.of("Asia/Singapore"))
.minusDays(6);
long diff = ChronoUnit.DAYS.between(sixDaysBehind, now);
assertEquals(diff, 6);
}

View File

@@ -1,12 +1,16 @@
package com.baeldung.date.comparison;
import org.junit.Test;
import java.time.*;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import org.junit.Test;
public class Java8DateTimeApiGeneralComparisonsUnitTest {
@Test
@@ -54,10 +58,8 @@ public class Java8DateTimeApiGeneralComparisonsUnitTest {
@Test
public void givenZonedDateTimes_whenComparing_thenAssertsPass() {
ZonedDateTime timeInNewYork = ZonedDateTime.of(2019, 8, 10, 8, 0, 0, 0,
ZoneId.of("America/New_York"));
ZonedDateTime timeInBerlin = ZonedDateTime.of(2019, 8, 10, 14, 0, 0, 0,
ZoneId.of("Europe/Berlin"));
ZonedDateTime timeInNewYork = ZonedDateTime.of(2019, 8, 10, 8, 0, 0, 0, ZoneId.of("America/New_York"));
ZonedDateTime timeInBerlin = ZonedDateTime.of(2019, 8, 10, 14, 0, 0, 0, ZoneId.of("Europe/Berlin"));
assertThat(timeInNewYork.isAfter(timeInBerlin), is(false));
assertThat(timeInNewYork.isBefore(timeInBerlin), is(false));
@@ -80,4 +82,14 @@ public class Java8DateTimeApiGeneralComparisonsUnitTest {
assertThat(firstTime.compareTo(secondTime), is(-1));
}
@Test
public void givenMinMaxLocalTimes_whenComparing_thenAssertsPass() {
LocalTime minTime = LocalTime.MIN;
LocalTime time = LocalTime.of(8, 30);
LocalTime maxTime = LocalTime.MAX;
assertThat(minTime.isBefore(time), is(true));
assertThat(time.isBefore(maxTime), is(true));
}
}

View File

@@ -1,16 +1,39 @@
package com.baeldung.dateapi;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
import org.junit.Test;
public class JavaDurationUnitTest {
@Test
public void givenATimePlus30Seconds_whenRequestingDuration_thenExpect30() {
LocalTime initialTime = LocalTime.of(6, 30, 0);
LocalTime finalTime = initialTime.plus(Duration.ofSeconds(30));
long seconds = Duration.between(initialTime, finalTime)
.getSeconds();
assertThat(seconds).isEqualTo(30);
}
@Test
public void givenATimePlus30Seconds_whenRequestingSecondsBetween_thenExpect30() {
LocalTime initialTime = LocalTime.of(6, 30, 0);
LocalTime finalTime = initialTime.plus(Duration.ofSeconds(30));
long seconds = ChronoUnit.SECONDS.between(initialTime, finalTime);
assertThat(seconds).isEqualTo(30);
}
@Test
public void test2() {
Instant start = Instant.parse("2017-10-03T10:15:30.00Z");
@@ -29,11 +52,15 @@ public class JavaDurationUnitTest {
Duration fromMinutes = Duration.ofMinutes(60);
assertEquals(1, fromMinutes.toHours());
assertEquals(120, duration.plusSeconds(60).getSeconds());
assertEquals(30, duration.minusSeconds(30).getSeconds());
assertEquals(120, duration.plusSeconds(60)
.getSeconds());
assertEquals(30, duration.minusSeconds(30)
.getSeconds());
assertEquals(120, duration.plus(60, ChronoUnit.SECONDS).getSeconds());
assertEquals(30, duration.minus(30, ChronoUnit.SECONDS).getSeconds());
assertEquals(120, duration.plus(60, ChronoUnit.SECONDS)
.getSeconds());
assertEquals(30, duration.minus(30, ChronoUnit.SECONDS)
.getSeconds());
Duration fromChar1 = Duration.parse("P1DT1H10M10.5S");
Duration fromChar2 = Duration.parse("PT10M");

View File

@@ -1,18 +1,41 @@
package com.baeldung.dateapi;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import java.time.LocalDate;
import java.time.Period;
import java.time.temporal.ChronoUnit;
import org.apache.log4j.Logger;
import org.junit.Test;
import java.time.LocalDate;
import java.time.Period;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
public class JavaPeriodUnitTest {
private static final Logger LOG = Logger.getLogger(JavaPeriodUnitTest.class);
@Test
public void givenADatePlus5Days_whenRequestingPeriod_thenExpectFive() {
LocalDate initialDate = LocalDate.parse("2007-05-10");
LocalDate finalDate = initialDate.plus(Period.ofDays(5));
int days = Period.between(initialDate, finalDate)
.getDays();
assertThat(days).isEqualTo(5);
}
@Test
public void givenADatePlus5Days_whenRequestingDaysBetween_thenExpectFive() {
LocalDate initialDate = LocalDate.parse("2007-05-10");
LocalDate finalDate = initialDate.plus(Period.ofDays(5));
long days = ChronoUnit.DAYS.between(initialDate, finalDate);
assertThat(days).isEqualTo(5);
}
@Test
public void whenTestPeriod_thenOk() {
@@ -24,8 +47,10 @@ public class JavaPeriodUnitTest {
LOG.info(String.format("Years:%d months:%d days:%d", period.getYears(), period.getMonths(), period.getDays()));
assertFalse(period.isNegative());
assertEquals(56, period.plusDays(50).getDays());
assertEquals(9, period.minusMonths(2).getMonths());
assertEquals(56, period.plusDays(50)
.getDays());
assertEquals(9, period.minusMonths(2)
.getMonths());
Period fromUnits = Period.of(3, 10, 10);
Period fromDays = Period.ofDays(50);

View File

@@ -0,0 +1,36 @@
package com.baeldung.datetime;
import static org.assertj.core.api.Assertions.assertThat;
import java.time.LocalDateTime;
import java.time.Month;
import java.time.format.FormatStyle;
import java.util.Locale;
import org.junit.Test;
public class UseDateTimeFormatterUnitTest {
private final UseDateTimeFormatter subject = new UseDateTimeFormatter();
private final LocalDateTime localDateTime = LocalDateTime.of(2015, Month.JANUARY, 25, 6, 30);
@Test
public void givenALocalDate_whenFormattingAsIso_thenPass() {
String result = subject.formatAsIsoDate(localDateTime);
assertThat(result).isEqualTo("2015-01-25");
}
@Test
public void givenALocalDate_whenFormattingWithPattern_thenPass() {
String result = subject.formatCustom(localDateTime, "yyyy/MM/dd");
assertThat(result).isEqualTo("2015/01/25");
}
@Test
public void givenALocalDate_whenFormattingWithStyleAndLocale_thenPass() {
String result = subject.formatWithStyleAndLocale(localDateTime, FormatStyle.MEDIUM, Locale.UK);
assertThat(result).isEqualTo("25 Jan 2015, 06:30:00");
}
}

View File

@@ -7,12 +7,13 @@ import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Month;
import java.time.ZoneOffset;
import org.junit.Test;
public class UseLocalDateTimeUnitTest {
UseLocalDateTime useLocalDateTime = new UseLocalDateTime();
private UseLocalDateTime useLocalDateTime = new UseLocalDateTime();
@Test
public void givenString_whenUsingParse_thenLocalDateTime() {
@@ -33,4 +34,28 @@ public class UseLocalDateTimeUnitTest {
assertThat(endOfDayFromGivenDirectly.toLocalTime()).isEqualTo(LocalTime.MAX);
assertThat(endOfDayFromGivenDirectly.toString()).isEqualTo("2018-06-23T23:59:59.999999999");
}
@Test
public void givenLocalDateTimeInFebruary_whenRequestingMonth_thenMonthIsFebruary() {
LocalDateTime givenLocalDateTime = LocalDateTime.of(2015, Month.FEBRUARY, 20, 6, 30);
assertThat(givenLocalDateTime.getMonth()).isEqualTo(Month.FEBRUARY);
}
@Test
public void givenLocalDateTime_whenManipulating_thenResultIsAsExpected() {
LocalDateTime givenLocalDateTime = LocalDateTime.parse("2015-02-20T06:30:00");
LocalDateTime manipulatedLocalDateTime = givenLocalDateTime.plusDays(1);
manipulatedLocalDateTime = manipulatedLocalDateTime.minusHours(2);
assertThat(manipulatedLocalDateTime).isEqualTo(LocalDateTime.of(2015, Month.FEBRUARY, 21, 4, 30));
}
@Test
public void whenRequestTimeFromEpoch_thenResultIsAsExpected() {
LocalDateTime result = useLocalDateTime.ofEpochSecond(1465817690, ZoneOffset.UTC);
assertThat(result.toString()).isEqualTo("2016-06-13T11:34:50");
}
}

View File

@@ -12,7 +12,7 @@ import org.junit.Test;
public class UseLocalDateUnitTest {
UseLocalDate useLocalDate = new UseLocalDate();
private UseLocalDate useLocalDate = new UseLocalDate();
@Test
public void givenValues_whenUsingFactoryOf_thenLocalDate() {
@@ -88,4 +88,31 @@ public class UseLocalDateUnitTest {
assertThat(endOfDayWithMax.toString()).isEqualTo("2018-06-23T23:59:59.999999999");
}
@Test
public void givenTheYear2000_whenCheckingForLeapYear_thenReturnTrue() {
LocalDate given = LocalDate.parse("2000-06-23");
boolean leapYear = useLocalDate.isLeapYear(given);
assertThat(leapYear).isEqualTo(true);
}
@Test
public void givenTheYear2004_whenCheckingForLeapYear_thenReturnTrue() {
LocalDate given = LocalDate.parse("2004-06-23");
boolean leapYear = useLocalDate.isLeapYear(given);
assertThat(leapYear).isEqualTo(true);
}
@Test
public void givenTheYear2019_whenCheckingForLeapYear_thenReturnFalse() {
LocalDate given = LocalDate.parse("2019-06-23");
boolean leapYear = useLocalDate.isLeapYear(given);
assertThat(leapYear).isEqualTo(false);
}
}

View File

@@ -7,21 +7,30 @@ import org.junit.Test;
public class UseLocalTimeUnitTest {
UseLocalTime useLocalTime = new UseLocalTime();
private UseLocalTime useLocalTime = new UseLocalTime();
@Test
public void givenValues_whenUsingFactoryOf_thenLocalTime() {
Assert.assertEquals("07:07:07", useLocalTime.getLocalTimeUsingFactoryOfMethod(7, 7, 7).toString());
Assert.assertEquals("07:07:07", useLocalTime.getLocalTimeUsingFactoryOfMethod(7, 7, 7)
.toString());
}
@Test
public void givenValues_whenUsingFactoryOfWithoutSeconds_thenLocalTime() {
Assert.assertEquals("07:07", useLocalTime.getLocalTimeUsingFactoryOfMethod(7, 7)
.toString());
}
@Test
public void givenString_whenUsingParse_thenLocalTime() {
Assert.assertEquals("06:30", useLocalTime.getLocalTimeUsingParseMethod("06:30").toString());
Assert.assertEquals("06:30", useLocalTime.getLocalTimeUsingParseMethod("06:30")
.toString());
}
@Test
public void givenTime_whenAddHour_thenLocalTime() {
Assert.assertEquals("07:30", useLocalTime.addAnHour(LocalTime.of(6, 30)).toString());
Assert.assertEquals("07:30", useLocalTime.addAnHour(LocalTime.of(6, 30))
.toString());
}
@Test

View File

@@ -0,0 +1,24 @@
package com.baeldung.datetime;
import static org.assertj.core.api.Assertions.assertThat;
import java.time.LocalDateTime;
import java.time.Month;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import org.junit.Test;
public class UseOffsetDateTimeUnitTest {
private final UseOffsetDateTime subject = new UseOffsetDateTime();
@Test
public void givenAZoneOffSetAndLocalDateTime_whenCombing_thenValidResult() {
ZoneOffset offset = ZoneOffset.of("+02:00");
LocalDateTime localDateTime = LocalDateTime.of(2015, Month.FEBRUARY, 20, 6, 30);
OffsetDateTime result = subject.offsetOfLocalDateTimeAndOffset(localDateTime, offset);
assertThat(result.toString()).isEqualTo("2015-02-20T06:30+02:00");
}
}

View File

@@ -0,0 +1,33 @@
package com.baeldung.datetime;
import static org.assertj.core.api.Assertions.assertThat;
import java.time.LocalDateTime;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import org.junit.Test;
public class UseToInstantUnitTest {
private UseToInstant subject = new UseToInstant();
@Test
public void givenAGregorianCalenderDate_whenConvertingToLocalDate_thenAsExpected() {
GregorianCalendar givenCalender = new GregorianCalendar(2018, Calendar.JULY, 28);
LocalDateTime localDateTime = subject.convertDateToLocalDate(givenCalender);
assertThat(localDateTime).isEqualTo("2018-07-28T00:00:00");
}
@Test
public void givenADate_whenConvertingToLocalDate_thenAsExpected() {
Date givenDate = new Date(1465817690000L);
LocalDateTime localDateTime = subject.convertDateToLocalDate(givenDate);
assertThat(localDateTime).isEqualTo("2016-06-13T13:34:50");
}
}

View File

@@ -7,13 +7,14 @@ import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Set;
import org.junit.Assert;
import org.junit.Test;
public class UseZonedDateTimeUnitTest {
UseZonedDateTime zonedDateTime = new UseZonedDateTime();
private UseZonedDateTime zonedDateTime = new UseZonedDateTime();
@Test
public void givenZoneId_thenZonedDateTime() {
@@ -22,6 +23,13 @@ public class UseZonedDateTimeUnitTest {
Assert.assertEquals(zoneId, ZoneId.from(zonedDatetime));
}
@Test
public void whenRequestingZones_thenAtLeastOneIsReturned() {
Set<String> allZoneIds = ZoneId.getAvailableZoneIds();
assertThat(allZoneIds.size()).isGreaterThan(1);
}
@Test
public void givenLocalDateOrZoned_whenSettingStartOfDay_thenReturnMidnightInAllCases() {
LocalDate given = LocalDate.parse("2018-06-23");
@@ -42,4 +50,15 @@ public class UseZonedDateTimeUnitTest {
assertThat(startOfOfDayWithMethod.toLocalTime()
.toString()).isEqualTo("00:00");
}
@Test
public void givenAStringWithTimeZone_whenParsing_thenEqualsExpected() {
ZonedDateTime resultFromString = zonedDateTime.getZonedDateTimeUsingParseMethod("2015-05-03T10:15:30+01:00[Europe/Paris]");
ZonedDateTime resultFromLocalDateTime = ZonedDateTime.of(2015, 5, 3, 11, 15, 30, 0, ZoneId.of("Europe/Paris"));
assertThat(resultFromString.getZone()).isEqualTo(ZoneId.of("Europe/Paris"));
assertThat(resultFromLocalDateTime.getZone()).isEqualTo(ZoneId.of("Europe/Paris"));
assertThat(resultFromString).isEqualTo(resultFromLocalDateTime);
}
}