Merge branch 'master' into BAEL-16633
This commit is contained in:
6
core-java-modules/core-java-9-streams/README.md
Normal file
6
core-java-modules/core-java-9-streams/README.md
Normal file
@@ -0,0 +1,6 @@
|
||||
## Core Java 9 streams
|
||||
|
||||
This module contains articles about Java 9 streams
|
||||
|
||||
### Relevant Articles:
|
||||
- [How to Break from Java Stream forEach](https://www.baeldung.com/java-break-stream-foreach)
|
||||
31
core-java-modules/core-java-9-streams/pom.xml
Normal file
31
core-java-modules/core-java-9-streams/pom.xml
Normal file
@@ -0,0 +1,31 @@
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>core-java-9-streams</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<name>core-java-9-streams</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-java</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../../parent-java</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>core-java-9-streams</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
</properties>
|
||||
</project>
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.baeldung.streams.breakforeach;
|
||||
|
||||
import java.util.Spliterator;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public class CustomForEach {
|
||||
|
||||
public static class Breaker {
|
||||
private boolean shouldBreak = false;
|
||||
|
||||
public void stop() {
|
||||
shouldBreak = true;
|
||||
}
|
||||
|
||||
boolean get() {
|
||||
return shouldBreak;
|
||||
}
|
||||
}
|
||||
|
||||
public static <T> void forEach(Stream<T> stream, BiConsumer<T, Breaker> consumer) {
|
||||
Spliterator<T> spliterator = stream.spliterator();
|
||||
boolean hadNext = true;
|
||||
Breaker breaker = new Breaker();
|
||||
|
||||
while (hadNext && !breaker.get()) {
|
||||
hadNext = spliterator.tryAdvance(elem -> {
|
||||
consumer.accept(elem, breaker);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.baeldung.streams.breakforeach;
|
||||
|
||||
import java.util.Spliterator;
|
||||
import java.util.Spliterators;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Predicate;
|
||||
|
||||
public class CustomSpliterator<T> extends Spliterators.AbstractSpliterator<T> {
|
||||
|
||||
private Spliterator<T> splitr;
|
||||
private Predicate<T> predicate;
|
||||
private boolean isMatched = true;
|
||||
|
||||
public CustomSpliterator(Spliterator<T> splitr, Predicate<T> predicate) {
|
||||
super(splitr.estimateSize(), 0);
|
||||
this.splitr = splitr;
|
||||
this.predicate = predicate;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean tryAdvance(Consumer<? super T> consumer) {
|
||||
boolean hadNext = splitr.tryAdvance(elem -> {
|
||||
if (predicate.test(elem) && isMatched) {
|
||||
consumer.accept(elem);
|
||||
} else {
|
||||
isMatched = false;
|
||||
}
|
||||
});
|
||||
return hadNext && isMatched;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.baeldung.streams.breakforeach;
|
||||
|
||||
import java.util.function.Predicate;
|
||||
import java.util.stream.Stream;
|
||||
import java.util.stream.StreamSupport;
|
||||
|
||||
public class CustomTakeWhile {
|
||||
|
||||
public static <T> Stream<T> takeWhile(Stream<T> stream, Predicate<T> predicate) {
|
||||
CustomSpliterator<T> customSpliterator = new CustomSpliterator<>(stream.spliterator(), predicate);
|
||||
return StreamSupport.stream(customSpliterator, false);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.baeldung.streams.breakforeach;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static java.util.Arrays.asList;
|
||||
|
||||
public class TakeWhileExample {
|
||||
|
||||
public static void takeWhileJava9() {
|
||||
Stream.of("cat", "dog", "elephant", "fox", "rabbit", "duck")
|
||||
.takeWhile(n -> n.length() % 2 != 0)
|
||||
.forEach(System.out::println); // cat, dog
|
||||
}
|
||||
|
||||
public static void plainForLoopWithBreak() {
|
||||
List<String> list = asList("cat", "dog", "elephant", "fox", "rabbit", "duck");
|
||||
for (int i = 0; i < list.size(); i++) {
|
||||
String item = list.get(i);
|
||||
if (item.length() % 2 == 0) {
|
||||
break;
|
||||
}
|
||||
System.out.println(item);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.baeldung.streams.breakforeach;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static java.util.Arrays.asList;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class BreakFromStreamForEachUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenCustomTakeWhileIsCalled_ThenCorrectItemsAreReturned() {
|
||||
Stream<String> initialStream = Stream.of("cat", "dog", "elephant", "fox", "rabbit", "duck");
|
||||
|
||||
List<String> result = CustomTakeWhile.takeWhile(initialStream, x -> x.length() % 2 != 0)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
assertEquals(asList("cat", "dog"), result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCustomForEachIsCalled_ThenCorrectItemsAreReturned() {
|
||||
Stream<String> initialStream = Stream.of("cat", "dog", "elephant", "fox", "rabbit", "duck");
|
||||
List<String> result = new ArrayList<>();
|
||||
|
||||
CustomForEach.forEach(initialStream, (elem, breaker) -> {
|
||||
if (elem.length() % 2 == 0) {
|
||||
breaker.stop();
|
||||
} else {
|
||||
result.add(elem);
|
||||
}
|
||||
});
|
||||
|
||||
assertEquals(asList("cat", "dog"), result);
|
||||
}
|
||||
|
||||
}
|
||||
15
core-java-modules/core-java-datetime-computations/README.md
Normal file
15
core-java-modules/core-java-datetime-computations/README.md
Normal file
@@ -0,0 +1,15 @@
|
||||
## Java Date/time computations Cookbooks and Examples
|
||||
|
||||
This module contains articles about date and time computations in Java.
|
||||
|
||||
### Relevant Articles:
|
||||
- [Difference Between Two Dates in Java](http://www.baeldung.com/java-date-difference)
|
||||
- [Get Date Without Time in Java](http://www.baeldung.com/java-date-without-time)
|
||||
- [How to Get All Dates Between Two Dates?](http://www.baeldung.com/java-between-dates)
|
||||
- [Extracting Year, Month and Day from Date in Java](http://www.baeldung.com/java-year-month-day)
|
||||
- [Guide to java.util.GregorianCalendar](http://www.baeldung.com/java-gregorian-calendar)
|
||||
- [Handling Daylight Savings Time in Java](http://www.baeldung.com/java-daylight-savings)
|
||||
- [Calculate Age in Java](http://www.baeldung.com/java-get-age)
|
||||
- [Increment Date in Java](http://www.baeldung.com/java-increment-date)
|
||||
- [Add Hours To a Date In Java](http://www.baeldung.com/java-add-hours-date)
|
||||
- [Introduction to Joda-Time](http://www.baeldung.com/joda-time)
|
||||
71
core-java-modules/core-java-datetime-computations/pom.xml
Normal file
71
core-java-modules/core-java-datetime-computations/pom.xml
Normal file
@@ -0,0 +1,71 @@
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>core-java-datetime-computations</artifactId>
|
||||
<version>${project.parent.version}</version>
|
||||
<name>core-java-datetime-computations</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-java</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../../parent-java</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>joda-time</groupId>
|
||||
<artifactId>joda-time</artifactId>
|
||||
<version>${joda-time.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang3.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.darwinsys</groupId>
|
||||
<artifactId>hirondelle-date4j</artifactId>
|
||||
<version>RELEASE</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>core-java-datetime-computations</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>${maven.compiler.source}</source>
|
||||
<target>${maven.compiler.target}</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<joda-time.version>2.10</joda-time.version>
|
||||
<!-- testing -->
|
||||
<assertj.version>3.6.1</assertj.version>
|
||||
<maven.compiler.source>1.9</maven.compiler.source>
|
||||
<maven.compiler.target>1.9</maven.compiler.target>
|
||||
</properties>
|
||||
</project>
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.baeldung.date;
|
||||
|
||||
import java.text.DateFormat;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.time.LocalDate;
|
||||
import java.time.Period;
|
||||
import java.util.Date;
|
||||
import org.joda.time.Years;
|
||||
|
||||
public class AgeCalculator {
|
||||
|
||||
public int calculateAge(LocalDate birthDate, LocalDate currentDate) {
|
||||
// validate inputs ...
|
||||
return Period.between(birthDate, currentDate)
|
||||
.getYears();
|
||||
}
|
||||
|
||||
public int calculateAgeWithJodaTime(org.joda.time.LocalDate birthDate, org.joda.time.LocalDate currentDate) {
|
||||
// validate inputs ...
|
||||
Years age = Years.yearsBetween(birthDate, currentDate);
|
||||
return age.getYears();
|
||||
}
|
||||
|
||||
public int calculateAgeWithJava7(Date birthDate, Date currentDate) {
|
||||
// validate inputs ...
|
||||
DateFormat formatter = new SimpleDateFormat("yyyyMMdd");
|
||||
int d1 = Integer.parseInt(formatter.format(birthDate));
|
||||
int d2 = Integer.parseInt(formatter.format(currentDate));
|
||||
int age = (d2 - d1) / 10000;
|
||||
return age;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.baeldung.date;
|
||||
|
||||
import java.text.ParseException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.time.LocalDate;
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
|
||||
public class DateWithoutTime {
|
||||
|
||||
public static Date getDateWithoutTimeUsingCalendar() {
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.set(Calendar.HOUR_OF_DAY, 0);
|
||||
calendar.set(Calendar.MINUTE, 0);
|
||||
calendar.set(Calendar.SECOND, 0);
|
||||
calendar.set(Calendar.MILLISECOND, 0);
|
||||
|
||||
return calendar.getTime();
|
||||
}
|
||||
|
||||
public static Date getDateWithoutTimeUsingFormat() throws ParseException {
|
||||
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
|
||||
return formatter.parse(formatter.format(new Date()));
|
||||
}
|
||||
|
||||
public static LocalDate getLocalDate() {
|
||||
return LocalDate.now();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package com.baeldung.datetime;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
|
||||
import org.apache.commons.lang3.time.DateUtils;
|
||||
|
||||
public class AddHoursToDate {
|
||||
|
||||
public Date addHoursToJavaUtilDate(Date date, int hours) {
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.setTime(date);
|
||||
calendar.add(Calendar.HOUR_OF_DAY, hours);
|
||||
return calendar.getTime();
|
||||
}
|
||||
|
||||
public Date addHoursToDateUsingInstant(Date date, int hours) {
|
||||
return Date.from(date.toInstant()
|
||||
.plus(Duration.ofHours(hours)));
|
||||
}
|
||||
|
||||
public LocalDateTime addHoursToLocalDateTime(LocalDateTime localDateTime, int hours) {
|
||||
return localDateTime.plusHours(hours);
|
||||
}
|
||||
|
||||
public LocalDateTime subtractHoursToLocalDateTime(LocalDateTime localDateTime, int hours) {
|
||||
return localDateTime.minusHours(hours);
|
||||
}
|
||||
|
||||
public ZonedDateTime addHoursToZonedDateTime(ZonedDateTime zonedDateTime, int hours) {
|
||||
return zonedDateTime.plusHours(hours);
|
||||
}
|
||||
|
||||
public ZonedDateTime subtractHoursToZonedDateTime(ZonedDateTime zonedDateTime, int hours) {
|
||||
return zonedDateTime.minusHours(hours);
|
||||
}
|
||||
|
||||
public Instant addHoursToInstant(Instant instant, int hours) {
|
||||
return instant.plus(hours, ChronoUnit.HOURS);
|
||||
}
|
||||
|
||||
public Instant subtractHoursToInstant(Instant instant, int hours) {
|
||||
return instant.minus(hours, ChronoUnit.HOURS);
|
||||
}
|
||||
|
||||
public Date addHoursWithApacheCommons(Date date, int hours) {
|
||||
return DateUtils.addHours(date, hours);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.baeldung.datetime;
|
||||
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
|
||||
public class DateExtractYearMonthDayIntegerValues {
|
||||
|
||||
int getYear(Date date) {
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.setTime(date);
|
||||
|
||||
return calendar.get(Calendar.YEAR);
|
||||
}
|
||||
|
||||
int getMonth(Date date) {
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.setTime(date);
|
||||
|
||||
return calendar.get(Calendar.MONTH);
|
||||
}
|
||||
|
||||
int getDay(Date date) {
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.setTime(date);
|
||||
|
||||
return calendar.get(Calendar.DAY_OF_MONTH);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.baeldung.datetime;
|
||||
|
||||
import java.time.LocalDate;
|
||||
|
||||
public class LocalDateExtractYearMonthDayIntegerValues {
|
||||
|
||||
int getYear(LocalDate localDate) {
|
||||
return localDate.getYear();
|
||||
}
|
||||
|
||||
int getMonth(LocalDate localDate) {
|
||||
return localDate.getMonthValue();
|
||||
}
|
||||
|
||||
int getDay(LocalDate localDate) {
|
||||
return localDate.getDayOfMonth();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.baeldung.datetime;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
public class LocalDateTimeExtractYearMonthDayIntegerValues {
|
||||
|
||||
int getYear(LocalDateTime localDateTime) {
|
||||
return localDateTime.getYear();
|
||||
}
|
||||
|
||||
int getMonth(LocalDateTime localDateTime) {
|
||||
return localDateTime.getMonthValue();
|
||||
}
|
||||
|
||||
int getDay(LocalDateTime localDateTime) {
|
||||
return localDateTime.getDayOfMonth();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.baeldung.datetime;
|
||||
|
||||
import java.time.OffsetDateTime;
|
||||
|
||||
public class OffsetDateTimeExtractYearMonthDayIntegerValues {
|
||||
|
||||
int getYear(OffsetDateTime offsetDateTime) {
|
||||
return offsetDateTime.getYear();
|
||||
}
|
||||
|
||||
int getMonth(OffsetDateTime offsetDateTime) {
|
||||
return offsetDateTime.getMonthValue();
|
||||
}
|
||||
|
||||
int getDay(OffsetDateTime offsetDateTime) {
|
||||
return offsetDateTime.getDayOfMonth();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.baeldung.datetime;
|
||||
|
||||
import java.time.ZonedDateTime;
|
||||
|
||||
public class ZonedDateTimeExtractYearMonthDayIntegerValues {
|
||||
|
||||
int getYear(ZonedDateTime zonedDateTime) {
|
||||
return zonedDateTime.getYear();
|
||||
}
|
||||
|
||||
int getMonth(ZonedDateTime zonedDateTime) {
|
||||
return zonedDateTime.getMonthValue();
|
||||
}
|
||||
|
||||
int getDay(ZonedDateTime zonedDateTime) {
|
||||
return zonedDateTime.getDayOfMonth();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package com.baeldung.datetime.modify;
|
||||
|
||||
import org.apache.commons.lang3.time.DateUtils;
|
||||
import org.joda.time.DateTime;
|
||||
|
||||
import java.text.ParseException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.time.LocalDate;
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
public class DateIncrementer {
|
||||
private static final Logger log = Logger.getLogger(DateIncrementer.class.getName());
|
||||
private static final int INCREMENT_BY_IN_DAYS = 1;
|
||||
|
||||
public static String addOneDay(String date) {
|
||||
return LocalDate
|
||||
.parse(date)
|
||||
.plusDays(INCREMENT_BY_IN_DAYS)
|
||||
.toString();
|
||||
}
|
||||
|
||||
public static String addOneDayJodaTime(String date) {
|
||||
DateTime dateTime = new DateTime(date);
|
||||
return dateTime
|
||||
.plusDays(INCREMENT_BY_IN_DAYS)
|
||||
.toString("yyyy-MM-dd");
|
||||
}
|
||||
|
||||
public static String addOneDayCalendar(String date) throws ParseException {
|
||||
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
|
||||
Calendar c = Calendar.getInstance();
|
||||
c.setTime(sdf.parse(date));
|
||||
c.add(Calendar.DATE, 1);
|
||||
return sdf.format(c.getTime());
|
||||
}
|
||||
|
||||
public static String addOneDayApacheCommons(String date) throws ParseException {
|
||||
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
|
||||
Date incrementedDate = DateUtils.addDays(sdf.parse(date), 1);
|
||||
return sdf.format(incrementedDate);
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws ParseException {
|
||||
String date = LocalDate
|
||||
.now()
|
||||
.toString();
|
||||
log.info("Current date = " + date);
|
||||
|
||||
String incrementedDateJava8 = DateIncrementer.addOneDay(date);
|
||||
log.info("Date incremented by one day using (Java 8): " + incrementedDateJava8);
|
||||
|
||||
String incrementedDateJodaTime = DateIncrementer.addOneDayJodaTime(date);
|
||||
log.info("Date incremented by one day using (Joda-Time): " + incrementedDateJodaTime);
|
||||
|
||||
String incrementedDateCalendar = addOneDayCalendar(date);
|
||||
log.info("Date incremented by one day using (java.util.Calendar): " + incrementedDateCalendar);
|
||||
|
||||
String incrementedDateApacheCommons = addOneDayApacheCommons(date);
|
||||
log.info("Date incremented by one day using (Apache Commons DateUtils): " + incrementedDateApacheCommons);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package com.baeldung.gregorian.calendar;
|
||||
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.Calendar;
|
||||
import java.util.Collections;
|
||||
import java.util.Date;
|
||||
import java.util.GregorianCalendar;
|
||||
import java.util.HashSet;
|
||||
import java.util.Locale;
|
||||
import java.util.Set;
|
||||
import java.util.TimeZone;
|
||||
|
||||
import javax.xml.datatype.DatatypeConfigurationException;
|
||||
import javax.xml.datatype.DatatypeFactory;
|
||||
import javax.xml.datatype.XMLGregorianCalendar;
|
||||
|
||||
public class GregorianCalendarExample {
|
||||
|
||||
|
||||
public Date setMonth(GregorianCalendar calendar, int amount) {
|
||||
calendar.set(Calendar.MONTH, amount);
|
||||
return calendar.getTime();
|
||||
}
|
||||
|
||||
|
||||
public Date rollAdd(GregorianCalendar calendar, int amount) {
|
||||
calendar.roll(GregorianCalendar.MONTH, amount);
|
||||
return calendar.getTime();
|
||||
}
|
||||
|
||||
public boolean isLeapYearExample(int year) {
|
||||
GregorianCalendar cal = (GregorianCalendar) GregorianCalendar.getInstance();
|
||||
return cal.isLeapYear(year);
|
||||
}
|
||||
|
||||
|
||||
|
||||
public Date subtractDays(GregorianCalendar calendar, int daysToSubtract) {
|
||||
GregorianCalendar cal = calendar;
|
||||
cal.add(Calendar.DATE, -daysToSubtract);
|
||||
return cal.getTime();
|
||||
}
|
||||
|
||||
public Date addDays(GregorianCalendar calendar, int daysToAdd) {
|
||||
GregorianCalendar cal = calendar;
|
||||
cal.add(Calendar.DATE, daysToAdd);
|
||||
return cal.getTime();
|
||||
}
|
||||
|
||||
public XMLGregorianCalendar toXMLGregorianCalendar(GregorianCalendar calendar) throws DatatypeConfigurationException {
|
||||
DatatypeFactory datatypeFactory = DatatypeFactory.newInstance();
|
||||
return datatypeFactory.newXMLGregorianCalendar(calendar);
|
||||
}
|
||||
|
||||
public Date toDate(XMLGregorianCalendar calendar) {
|
||||
return calendar.toGregorianCalendar()
|
||||
.getTime();
|
||||
}
|
||||
|
||||
public int compareDates(GregorianCalendar firstDate, GregorianCalendar secondDate) {
|
||||
return firstDate.compareTo(secondDate);
|
||||
}
|
||||
|
||||
public String formatDate(GregorianCalendar calendar) {
|
||||
return calendar.toZonedDateTime()
|
||||
.format(DateTimeFormatter.ofPattern("d MMM uuuu"));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package com.baeldung.java9.time;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
import java.util.GregorianCalendar;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
public class TimeApi {
|
||||
|
||||
public static List<Date> getDatesBetweenUsingJava7(Date startDate, Date endDate) {
|
||||
List<Date> datesInRange = new ArrayList<Date>();
|
||||
Calendar calendar = new GregorianCalendar();
|
||||
calendar.setTime(startDate);
|
||||
|
||||
Calendar endCalendar = new GregorianCalendar();
|
||||
endCalendar.setTime(endDate);
|
||||
|
||||
while (calendar.before(endCalendar)) {
|
||||
Date result = calendar.getTime();
|
||||
datesInRange.add(result);
|
||||
calendar.add(Calendar.DATE, 1);
|
||||
}
|
||||
return datesInRange;
|
||||
}
|
||||
|
||||
public static List<LocalDate> getDatesBetweenUsingJava8(LocalDate startDate, LocalDate endDate) {
|
||||
long numOfDaysBetween = ChronoUnit.DAYS.between(startDate, endDate);
|
||||
return IntStream.iterate(0, i -> i + 1)
|
||||
.limit(numOfDaysBetween)
|
||||
.mapToObj(i -> startDate.plusDays(i))
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
public static List<LocalDate> getDatesBetweenUsingJava9(LocalDate startDate, LocalDate endDate) {
|
||||
return startDate.datesUntil(endDate).collect(Collectors.toList());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.baeldung.date;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import java.text.ParseException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.time.LocalDate;
|
||||
import java.util.Date;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class AgeCalculatorUnitTest {
|
||||
AgeCalculator ageCalculator = new AgeCalculator();
|
||||
|
||||
@Test
|
||||
public void givenLocalDate_whenCalculateAge_thenOk() {
|
||||
assertEquals(10, ageCalculator.calculateAge(LocalDate.of(2008, 5, 20), LocalDate.of(2018, 9, 20)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenJodaTime_whenCalculateAge_thenOk() {
|
||||
assertEquals(10, ageCalculator.calculateAgeWithJodaTime(new org.joda.time.LocalDate(2008, 5, 20), new org.joda.time.LocalDate(2018, 9, 20)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDate_whenCalculateAge_thenOk() throws ParseException {
|
||||
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");
|
||||
Date birthDate = sdf.parse("2008-05-20");
|
||||
Date currentDate = sdf.parse("2018-09-20");
|
||||
assertEquals(10, ageCalculator.calculateAgeWithJava7(birthDate, currentDate));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
package com.baeldung.date;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.text.ParseException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.time.Duration;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.Period;
|
||||
import java.time.ZoneId;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.Date;
|
||||
import java.util.Locale;
|
||||
import java.util.TimeZone;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class DateDiffUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenTwoDatesBeforeJava8_whenDifferentiating_thenWeGetSix() throws ParseException {
|
||||
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy", Locale.ENGLISH);
|
||||
Date firstDate = sdf.parse("06/24/2017");
|
||||
Date secondDate = sdf.parse("06/30/2017");
|
||||
|
||||
long diffInMillies = Math.abs(secondDate.getTime() - firstDate.getTime());
|
||||
long diff = TimeUnit.DAYS.convert(diffInMillies, TimeUnit.MILLISECONDS);
|
||||
|
||||
assertEquals(diff, 6);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoDatesInJava8_whenDifferentiating_thenWeGetSix() {
|
||||
LocalDate now = LocalDate.now();
|
||||
LocalDate sixDaysBehind = now.minusDays(6);
|
||||
|
||||
Period period = Period.between(now, sixDaysBehind);
|
||||
int diff = Math.abs(period.getDays());
|
||||
|
||||
assertEquals(diff, 6);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoDateTimesInJava8_whenDifferentiating_thenWeGetSix() {
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
LocalDateTime sixMinutesBehind = now.minusMinutes(6);
|
||||
|
||||
Duration duration = Duration.between(now, sixMinutesBehind);
|
||||
long diff = Math.abs(duration.toMinutes());
|
||||
|
||||
assertEquals(diff, 6);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoDateTimesInJava8_whenDifferentiatingInSeconds_thenWeGetTen() {
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
LocalDateTime tenSecondsLater = now.plusSeconds(10);
|
||||
|
||||
long diff = ChronoUnit.SECONDS.between(now, tenSecondsLater);
|
||||
|
||||
assertEquals(diff, 10);
|
||||
}
|
||||
|
||||
@Test
|
||||
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);
|
||||
long diff = ChronoUnit.DAYS.between(sixDaysBehind, now);
|
||||
assertEquals(diff, 6);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoDateTimesInJava8_whenDifferentiatingInSecondsUsingUntil_thenWeGetTen() {
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
LocalDateTime tenSecondsLater = now.plusSeconds(10);
|
||||
|
||||
long diff = now.until(tenSecondsLater, ChronoUnit.SECONDS);
|
||||
|
||||
assertEquals(diff, 10);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoDatesInJodaTime_whenDifferentiating_thenWeGetSix() {
|
||||
org.joda.time.LocalDate now = org.joda.time.LocalDate.now();
|
||||
org.joda.time.LocalDate sixDaysBehind = now.minusDays(6);
|
||||
|
||||
org.joda.time.Period period = new org.joda.time.Period(now, sixDaysBehind);
|
||||
long diff = Math.abs(period.getDays());
|
||||
|
||||
assertEquals(diff, 6);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoDateTimesInJodaTime_whenDifferentiating_thenWeGetSix() {
|
||||
org.joda.time.LocalDateTime now = org.joda.time.LocalDateTime.now();
|
||||
org.joda.time.LocalDateTime sixMinutesBehind = now.minusMinutes(6);
|
||||
|
||||
org.joda.time.Period period = new org.joda.time.Period(now, sixMinutesBehind);
|
||||
long diff = Math.abs(period.getDays());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoDatesInDate4j_whenDifferentiating_thenWeGetSix() {
|
||||
hirondelle.date4j.DateTime now = hirondelle.date4j.DateTime.now(TimeZone.getDefault());
|
||||
hirondelle.date4j.DateTime sixDaysBehind = now.minusDays(6);
|
||||
|
||||
long diff = Math.abs(now.numDaysFrom(sixDaysBehind));
|
||||
|
||||
assertEquals(diff, 6);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package com.baeldung.date;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.text.ParseException;
|
||||
import java.time.LocalDate;
|
||||
import java.time.OffsetDateTime;
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotEquals;
|
||||
|
||||
public class DateWithoutTimeUnitTest {
|
||||
|
||||
private static final long MILLISECONDS_PER_DAY = 24 * 60 * 60 * 1000;
|
||||
|
||||
@Test
|
||||
public void whenGettingDateWithoutTimeUsingCalendar_thenReturnDateWithoutTime() {
|
||||
Date dateWithoutTime = DateWithoutTime.getDateWithoutTimeUsingCalendar();
|
||||
|
||||
// first check the time is set to 0
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.setTime(dateWithoutTime);
|
||||
|
||||
assertEquals(0, calendar.get(Calendar.HOUR_OF_DAY));
|
||||
assertEquals(0, calendar.get(Calendar.MINUTE));
|
||||
assertEquals(0, calendar.get(Calendar.SECOND));
|
||||
assertEquals(0, calendar.get(Calendar.MILLISECOND));
|
||||
|
||||
// we get the day of the date
|
||||
int day = calendar.get(Calendar.DAY_OF_MONTH);
|
||||
|
||||
// if we add the mills of one day minus 1 we should get the same day
|
||||
calendar.setTimeInMillis(dateWithoutTime.getTime() + MILLISECONDS_PER_DAY - 1);
|
||||
assertEquals(day, calendar.get(Calendar.DAY_OF_MONTH));
|
||||
|
||||
// if we add one full day in millis we should get a different day
|
||||
calendar.setTimeInMillis(dateWithoutTime.getTime() + MILLISECONDS_PER_DAY);
|
||||
assertNotEquals(day, calendar.get(Calendar.DAY_OF_MONTH));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGettingDateWithoutTimeUsingFormat_thenReturnDateWithoutTime() throws ParseException {
|
||||
Date dateWithoutTime = DateWithoutTime.getDateWithoutTimeUsingFormat();
|
||||
|
||||
// first check the time is set to 0
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.setTime(dateWithoutTime);
|
||||
|
||||
assertEquals(0, calendar.get(Calendar.HOUR_OF_DAY));
|
||||
assertEquals(0, calendar.get(Calendar.MINUTE));
|
||||
assertEquals(0, calendar.get(Calendar.SECOND));
|
||||
assertEquals(0, calendar.get(Calendar.MILLISECOND));
|
||||
|
||||
// we get the day of the date
|
||||
int day = calendar.get(Calendar.DAY_OF_MONTH);
|
||||
|
||||
// if we add the mills of one day minus 1 we should get the same day
|
||||
calendar.setTimeInMillis(dateWithoutTime.getTime() + MILLISECONDS_PER_DAY - 1);
|
||||
assertEquals(day, calendar.get(Calendar.DAY_OF_MONTH));
|
||||
|
||||
// if we add one full day in millis we should get a different day
|
||||
calendar.setTimeInMillis(dateWithoutTime.getTime() + MILLISECONDS_PER_DAY);
|
||||
assertNotEquals(day, calendar.get(Calendar.DAY_OF_MONTH));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGettingLocalDate_thenReturnDateWithoutTime() {
|
||||
// get the local date
|
||||
LocalDate localDate = DateWithoutTime.getLocalDate();
|
||||
|
||||
// get the millis of our LocalDate
|
||||
long millisLocalDate = localDate
|
||||
.atStartOfDay()
|
||||
.toInstant(OffsetDateTime
|
||||
.now()
|
||||
.getOffset())
|
||||
.toEpochMilli();
|
||||
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
// if we add the millis of one day minus 1 we should get the same day
|
||||
calendar.setTimeInMillis(millisLocalDate + MILLISECONDS_PER_DAY - 1);
|
||||
assertEquals(localDate.getDayOfMonth(), calendar.get(Calendar.DAY_OF_MONTH));
|
||||
|
||||
// if we add one full day in millis we should get a different day
|
||||
calendar.setTimeInMillis(millisLocalDate + MILLISECONDS_PER_DAY);
|
||||
assertNotEquals(localDate.getDayOfMonth(), calendar.get(Calendar.DAY_OF_MONTH));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
package com.baeldung.datetime;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.Month;
|
||||
import java.time.ZoneId;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
import java.util.GregorianCalendar;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class AddHoursToDateUnitTest {
|
||||
|
||||
private final AddHoursToDate addHoursToDateObj = new AddHoursToDate();
|
||||
|
||||
@Test
|
||||
public void givenJavaUtilDate_whenPositiveHours_thenAddHours() {
|
||||
Date actualDate = new GregorianCalendar(2018, Calendar.JUNE, 25, 5, 0).getTime();
|
||||
Date expectedDate = new GregorianCalendar(2018, Calendar.JUNE, 25, 7, 0).getTime();
|
||||
|
||||
assertThat(addHoursToDateObj.addHoursToJavaUtilDate(actualDate, 2)).isEqualTo(expectedDate);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenJavaUtilDate_whenNegativeHours_thenMinusHours() {
|
||||
Date actualDate = new GregorianCalendar(2018, Calendar.JUNE, 25, 5, 0).getTime();
|
||||
Date expectedDate = new GregorianCalendar(2018, Calendar.JUNE, 25, 3, 0).getTime();
|
||||
|
||||
assertThat(addHoursToDateObj.addHoursToJavaUtilDate(actualDate, -2)).isEqualTo(expectedDate);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenJavaUtilDate_whenUsingToInstantAndPostiveHours_thenAddHours() {
|
||||
Date actualDate = new GregorianCalendar(2018, Calendar.JUNE, 25, 5, 0).getTime();
|
||||
Date expectedDate = new GregorianCalendar(2018, Calendar.JUNE, 25, 7, 0).getTime();
|
||||
|
||||
assertThat(addHoursToDateObj.addHoursToDateUsingInstant(actualDate, 2)).isEqualTo(expectedDate);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenJavaUtilDate_whenUsingToInstantAndNegativeHours_thenAddHours() {
|
||||
Date actualDate = new GregorianCalendar(2018, Calendar.JUNE, 25, 5, 0).getTime();
|
||||
Date expectedDate = new GregorianCalendar(2018, Calendar.JUNE, 25, 3, 0).getTime();
|
||||
|
||||
assertThat(addHoursToDateObj.addHoursToDateUsingInstant(actualDate, -2)).isEqualTo(expectedDate);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLocalDateTime_whenUsingAddHoursToLocalDateTime_thenAddHours() {
|
||||
LocalDateTime actualDateTime = LocalDateTime.of(2018, Month.JUNE, 25, 5, 0);
|
||||
LocalDateTime expectedDateTime = LocalDateTime.of(2018, Month.JUNE, 25, 7, 0);
|
||||
|
||||
assertThat(addHoursToDateObj.addHoursToLocalDateTime(actualDateTime, 2)).isEqualTo(expectedDateTime);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLocalDateTime_whenUsingMinusHoursToLocalDateTime_thenMinusHours() {
|
||||
LocalDateTime actualDateTime = LocalDateTime.of(2018, Month.JUNE, 25, 5, 0);
|
||||
LocalDateTime expectedDateTime = LocalDateTime.of(2018, Month.JUNE, 25, 3, 0);
|
||||
|
||||
assertThat(addHoursToDateObj.subtractHoursToLocalDateTime(actualDateTime, 2)).isEqualTo(expectedDateTime);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenZonedDateTime_whenUsingAddHoursToZonedDateTime_thenAddHours() {
|
||||
ZonedDateTime actualZonedDateTime = ZonedDateTime.of(LocalDateTime.of(2018, Month.JUNE, 25, 5, 0), ZoneId.systemDefault());
|
||||
ZonedDateTime expectedZonedDateTime = ZonedDateTime.of(LocalDateTime.of(2018, Month.JUNE, 25, 7, 0), ZoneId.systemDefault());
|
||||
|
||||
assertThat(addHoursToDateObj.addHoursToZonedDateTime(actualZonedDateTime, 2)).isEqualTo(expectedZonedDateTime);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenZonedDateTime_whenUsingMinusHoursToZonedDateTime_thenMinusHours() {
|
||||
ZonedDateTime actualZonedDateTime = ZonedDateTime.of(LocalDateTime.of(2018, Month.JUNE, 25, 5, 0), ZoneId.systemDefault());
|
||||
ZonedDateTime expectedZonedDateTime = ZonedDateTime.of(LocalDateTime.of(2018, Month.JUNE, 25, 3, 0), ZoneId.systemDefault());
|
||||
|
||||
assertThat(addHoursToDateObj.subtractHoursToZonedDateTime(actualZonedDateTime, 2)).isEqualTo(expectedZonedDateTime);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenJavaUtilDate_whenUsingPositiveHrsAndAddHoursWithApacheCommons_thenAddHours() {
|
||||
Date actualDate = new GregorianCalendar(2018, Calendar.JUNE, 25, 5, 0).getTime();
|
||||
Date expectedDate = new GregorianCalendar(2018, Calendar.JUNE, 25, 7, 0).getTime();
|
||||
|
||||
assertThat(addHoursToDateObj.addHoursWithApacheCommons(actualDate, 2)).isEqualTo(expectedDate);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenJavaUtilDate_whenUsingNegativeHrsAndAddHoursWithApacheCommons_thenMinusHours() {
|
||||
Date actualDate = new GregorianCalendar(2018, Calendar.JUNE, 25, 7, 0).getTime();
|
||||
Date expectedDate = new GregorianCalendar(2018, Calendar.JUNE, 25, 5, 0).getTime();
|
||||
|
||||
assertThat(addHoursToDateObj.addHoursWithApacheCommons(actualDate, -2)).isEqualTo(expectedDate);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInstant_whenUsingAddHoursToInstant_thenAddHours() {
|
||||
Instant actualValue = Instant.parse("2018-06-25T05:12:35Z");
|
||||
Instant expectedValue = Instant.parse("2018-06-25T07:12:35Z");
|
||||
|
||||
assertThat(addHoursToDateObj.addHoursToInstant(actualValue, 2)).isEqualTo(expectedValue);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInstant_whenUsingSubtractHoursToInstant_thenMinusHours() {
|
||||
Instant actualValue = Instant.parse("2018-06-25T07:12:35Z");
|
||||
Instant expectedValue = Instant.parse("2018-06-25T05:12:35Z");
|
||||
|
||||
assertThat(addHoursToDateObj.subtractHoursToInstant(actualValue, 2)).isEqualTo(expectedValue);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package com.baeldung.datetime;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.is;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import java.text.ParseException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Date;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
public class DateExtractYearMonthDayIntegerValuesUnitTest {
|
||||
|
||||
DateExtractYearMonthDayIntegerValues extractYearMonthDateIntegerValues = new DateExtractYearMonthDayIntegerValues();
|
||||
|
||||
Date date;
|
||||
|
||||
@Before
|
||||
public void setup() throws ParseException
|
||||
{
|
||||
date=new SimpleDateFormat("dd-MM-yyyy").parse("01-03-2018");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetYear_thenCorrectYear()
|
||||
{
|
||||
int actualYear=extractYearMonthDateIntegerValues.getYear(date);
|
||||
assertThat(actualYear,is(2018));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetMonth_thenCorrectMonth()
|
||||
{
|
||||
int actualMonth=extractYearMonthDateIntegerValues.getMonth(date);
|
||||
assertThat(actualMonth,is(02));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetDay_thenCorrectDay()
|
||||
{
|
||||
int actualDayOfMonth=extractYearMonthDateIntegerValues.getDay(date);
|
||||
assertThat(actualDayOfMonth,is(01));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package com.baeldung.datetime;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.is;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import java.time.LocalDate;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class LocalDateExtractYearMonthDayIntegerValuesUnitTest {
|
||||
|
||||
LocalDateExtractYearMonthDayIntegerValues localDateExtractYearMonthDayIntegerValues=new LocalDateExtractYearMonthDayIntegerValues();
|
||||
|
||||
LocalDate localDate=LocalDate.parse("2007-12-03");
|
||||
|
||||
@Test
|
||||
public void whenGetYear_thenCorrectYear()
|
||||
{
|
||||
int actualYear=localDateExtractYearMonthDayIntegerValues.getYear(localDate);
|
||||
assertThat(actualYear,is(2007));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetMonth_thenCorrectMonth()
|
||||
{
|
||||
int actualMonth=localDateExtractYearMonthDayIntegerValues.getMonth(localDate);
|
||||
assertThat(actualMonth,is(12));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetDay_thenCorrectDay()
|
||||
{
|
||||
int actualDayOfMonth=localDateExtractYearMonthDayIntegerValues.getDay(localDate);
|
||||
assertThat(actualDayOfMonth,is(03));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package com.baeldung.datetime;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.is;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class LocalDateTimeExtractYearMonthDayIntegerValuesUnitTest {
|
||||
|
||||
LocalDateTimeExtractYearMonthDayIntegerValues localDateTimeExtractYearMonthDayIntegerValues = new LocalDateTimeExtractYearMonthDayIntegerValues();
|
||||
|
||||
LocalDateTime localDateTime=LocalDateTime.parse("2007-12-03T10:15:30");
|
||||
|
||||
@Test
|
||||
public void whenGetYear_thenCorrectYear()
|
||||
{
|
||||
int actualYear=localDateTimeExtractYearMonthDayIntegerValues.getYear(localDateTime);
|
||||
assertThat(actualYear,is(2007));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetMonth_thenCorrectMonth()
|
||||
{
|
||||
int actualMonth=localDateTimeExtractYearMonthDayIntegerValues.getMonth(localDateTime);
|
||||
assertThat(actualMonth,is(12));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetDay_thenCorrectDay()
|
||||
{
|
||||
int actualDayOfMonth=localDateTimeExtractYearMonthDayIntegerValues.getDay(localDateTime);
|
||||
assertThat(actualDayOfMonth,is(03));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package com.baeldung.datetime;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.is;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import java.time.OffsetDateTime;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class OffsetDateTimeExtractYearMonthDayIntegerValuesUnitTest {
|
||||
|
||||
OffsetDateTimeExtractYearMonthDayIntegerValues offsetDateTimeExtractYearMonthDayIntegerValues = new OffsetDateTimeExtractYearMonthDayIntegerValues();
|
||||
|
||||
OffsetDateTime offsetDateTime=OffsetDateTime.parse("2007-12-03T10:15:30+01:00");
|
||||
|
||||
@Test
|
||||
public void whenGetYear_thenCorrectYear()
|
||||
{
|
||||
int actualYear=offsetDateTimeExtractYearMonthDayIntegerValues.getYear(offsetDateTime);
|
||||
assertThat(actualYear,is(2007));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetMonth_thenCorrectMonth()
|
||||
{
|
||||
int actualMonth=offsetDateTimeExtractYearMonthDayIntegerValues.getMonth(offsetDateTime);
|
||||
assertThat(actualMonth,is(12));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetDay_thenCorrectDay()
|
||||
{
|
||||
int actualDayOfMonth=offsetDateTimeExtractYearMonthDayIntegerValues.getDay(offsetDateTime);
|
||||
assertThat(actualDayOfMonth,is(03));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package com.baeldung.datetime;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.is;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import java.time.ZonedDateTime;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class ZonedDateTimeExtractYearMonthDayIntegerValuesUnitTest {
|
||||
|
||||
ZonedDateTimeExtractYearMonthDayIntegerValues zonedDateTimeExtractYearMonthDayIntegerValues = new ZonedDateTimeExtractYearMonthDayIntegerValues();
|
||||
|
||||
ZonedDateTime zonedDateTime=ZonedDateTime.parse("2007-12-03T10:15:30+01:00");
|
||||
|
||||
@Test
|
||||
public void whenGetYear_thenCorrectYear()
|
||||
{
|
||||
int actualYear=zonedDateTimeExtractYearMonthDayIntegerValues.getYear(zonedDateTime);
|
||||
assertThat(actualYear,is(2007));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetMonth_thenCorrectMonth()
|
||||
{
|
||||
int actualMonth=zonedDateTimeExtractYearMonthDayIntegerValues.getMonth(zonedDateTime);
|
||||
assertThat(actualMonth,is(12));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetDay_thenCorrectDay()
|
||||
{
|
||||
int actualDayOfMonth=zonedDateTimeExtractYearMonthDayIntegerValues.getDay(zonedDateTime);
|
||||
assertThat(actualDayOfMonth,is(03));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.baeldung.datetime.modify;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class DateIncrementerUnitTest {
|
||||
private final static String DATE_TO_INCREMENT = "2018-07-03";
|
||||
private final static String EXPECTED_DATE = "2018-07-04";
|
||||
|
||||
@Test
|
||||
public void givenDate_whenUsingJava8_thenAddOneDay() throws Exception {
|
||||
String incrementedDate = DateIncrementer.addOneDay(DATE_TO_INCREMENT);
|
||||
assertEquals(EXPECTED_DATE, incrementedDate);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDate_whenUsingJodaTime_thenAddOneDay() throws Exception {
|
||||
String incrementedDate = DateIncrementer.addOneDayJodaTime(DATE_TO_INCREMENT);
|
||||
assertEquals(EXPECTED_DATE, incrementedDate);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDate_whenUsingCalendar_thenAddOneDay() throws Exception {
|
||||
String incrementedDate = DateIncrementer.addOneDayCalendar(DATE_TO_INCREMENT);
|
||||
assertEquals(EXPECTED_DATE, incrementedDate);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDate_whenUsingApacheCommons_thenAddOneDay() throws Exception {
|
||||
String incrementedDate = DateIncrementer.addOneDayApacheCommons(DATE_TO_INCREMENT);
|
||||
assertEquals(EXPECTED_DATE, incrementedDate);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package com.baeldung.dst;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.text.DateFormat;
|
||||
import java.text.ParseException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
import java.util.Locale;
|
||||
import java.util.TimeZone;
|
||||
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
|
||||
public class DaylightSavingTimeExamplesUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenItalianTimeZone_WhenDSTHappens_ThenCorrectlyShiftTimeZone() throws ParseException {
|
||||
TimeZone.setDefault(TimeZone.getTimeZone("Europe/Rome"));
|
||||
|
||||
TimeZone tz = TimeZone.getTimeZone("Europe/Rome");
|
||||
Calendar cal = Calendar.getInstance(tz, Locale.ITALIAN);
|
||||
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.ITALIAN);
|
||||
Date dateBeforeDST = df.parse("2018-03-25 01:55");
|
||||
prettyPrint(cal.getTimeZone());
|
||||
|
||||
cal.setTime(dateBeforeDST);
|
||||
System.out.println("Before DST (00:55 UTC - 01:55 GMT+1) = " + dateBeforeDST);
|
||||
|
||||
System.out.println("With this Calendar " + (cal.get(Calendar.ZONE_OFFSET) + cal.get(Calendar.DST_OFFSET)) / (60 * 1000) + " minutes must be added to UTC (GMT TimeZone) to get a correct date for this TimeZone\n");
|
||||
assertThat(cal.get(Calendar.ZONE_OFFSET)).isEqualTo(3600000);
|
||||
assertThat(cal.get(Calendar.DST_OFFSET)).isEqualTo(0);
|
||||
|
||||
cal.add(Calendar.MINUTE, 10);
|
||||
|
||||
Date dateAfterDST = cal.getTime();
|
||||
|
||||
System.out.println(" After DST (01:05 UTC - 03:05 GMT+2) = " + dateAfterDST);
|
||||
System.out.println("With this Calendar " + (cal.get(Calendar.ZONE_OFFSET) + cal.get(Calendar.DST_OFFSET)) / (60 * 1000) + " minutes must be added to UTC (GMT TimeZone) to get a correct date for this TimeZone\n");
|
||||
assertThat(cal.get(Calendar.DST_OFFSET)).isEqualTo(3600000);
|
||||
assertThat(dateAfterDST).isEqualTo(df.parse("2018-03-25 03:05"));
|
||||
|
||||
Long deltaBetweenDatesInMillis = dateAfterDST.getTime() - dateBeforeDST.getTime();
|
||||
Long tenMinutesInMillis = (1000L * 60 * 10);
|
||||
assertThat(deltaBetweenDatesInMillis).isEqualTo(tenMinutesInMillis);
|
||||
}
|
||||
|
||||
private void prettyPrint(TimeZone tz) {
|
||||
|
||||
//@formatter:off
|
||||
System.out.println(String.format(
|
||||
" Zone ID = %s (%s)\n"
|
||||
+ " RawOffset = %s minutes\n"
|
||||
+ " DST = %s minutes\n"
|
||||
+ " -----------------------------------------",
|
||||
tz.getID(), tz.getDisplayName(), tz.getRawOffset()/60000, tz.getDSTSavings()/60000));
|
||||
//@formatter:on
|
||||
}
|
||||
|
||||
@Test
|
||||
@Ignore
|
||||
public void whenIterating_ThenPrintAllTimeZones() {
|
||||
for (String id : TimeZone.getAvailableIDs()) {
|
||||
TimeZone tz = TimeZone.getTimeZone(id);
|
||||
prettyPrint(tz);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package com.baeldung.dst;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.text.ParseException;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.TimeZone;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class DaylightSavingTimeJavaTimeExamplesUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenItalianTimeZone_WhenDSTHappens_ThenCorrectlyShiftTimeZone() throws ParseException {
|
||||
ZoneId italianZoneId = ZoneId.of("Europe/Rome");
|
||||
|
||||
LocalDateTime localDateTimeBeforeDST = LocalDateTime.of(2018, 3, 25, 1, 55);
|
||||
System.out.println(localDateTimeBeforeDST);
|
||||
assertThat(localDateTimeBeforeDST.toString()).isEqualTo("2018-03-25T01:55");
|
||||
|
||||
ZonedDateTime zonedDateTimeBeforeDST = localDateTimeBeforeDST.atZone(italianZoneId);
|
||||
prettyPrint(zonedDateTimeBeforeDST);
|
||||
assertThat(zonedDateTimeBeforeDST.toString()).isEqualTo("2018-03-25T01:55+01:00[Europe/Rome]");
|
||||
|
||||
ZonedDateTime zonedDateTimeAfterDST = zonedDateTimeBeforeDST.plus(10, ChronoUnit.MINUTES);
|
||||
prettyPrint(zonedDateTimeAfterDST);
|
||||
assertThat(zonedDateTimeAfterDST.toString()).isEqualTo("2018-03-25T03:05+02:00[Europe/Rome]");
|
||||
|
||||
Long deltaBetweenDatesInMinutes = ChronoUnit.MINUTES.between(zonedDateTimeBeforeDST, zonedDateTimeAfterDST);
|
||||
assertThat(deltaBetweenDatesInMinutes).isEqualTo(10);
|
||||
|
||||
}
|
||||
|
||||
private void prettyPrint(ZonedDateTime zdt) {
|
||||
//@formatter:off
|
||||
System.out.println(String.format(
|
||||
" ZonedDateTime = %s\n"
|
||||
+ " Zone ID = %s (%s)\n"
|
||||
+ " RawOffset = %s minutes\n"
|
||||
+ " -----------------------------------------",
|
||||
zdt, zdt.getZone(), zdt.getZone().getId(), zdt.getOffset().getTotalSeconds()/60));
|
||||
//@formatter:on
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCounting_ThenPrintDifferencesBetweenAPIs() {
|
||||
System.out.println("Total java.time.ZoneId count : " + ZoneId.getAvailableZoneIds()
|
||||
.size());
|
||||
System.out.println("Total java.util.TimeZone Id count : " + TimeZone.getAvailableIDs().length);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
package com.baeldung.gregorian.calendar;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
import java.util.GregorianCalendar;
|
||||
import java.util.Locale;
|
||||
import java.util.TimeZone;
|
||||
|
||||
import javax.xml.datatype.DatatypeConfigurationException;
|
||||
import javax.xml.datatype.DatatypeFactory;
|
||||
import javax.xml.datatype.XMLGregorianCalendar;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.gregorian.calendar.GregorianCalendarExample;
|
||||
|
||||
public class GregorianCalendarTester {
|
||||
|
||||
@Test
|
||||
public void test_Calendar_Return_Type_Valid() {
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
assert ("gregory".equals(calendar.getCalendarType()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_Calendar_Return_Type_InValid() {
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
assertNotEquals("gregorys", calendar.getCalendarType());
|
||||
}
|
||||
|
||||
@Test(expected = ClassCastException.class)
|
||||
public void test_Class_Cast_Exception() {
|
||||
TimeZone tz = TimeZone.getTimeZone("GMT+9:00");
|
||||
Locale loc = new Locale("ja", "JP", "JP");
|
||||
Calendar calendar = Calendar.getInstance(loc);
|
||||
GregorianCalendar gc = (GregorianCalendar) calendar;
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_Getting_Calendar_information() {
|
||||
GregorianCalendar calendar = new GregorianCalendar(2018, 5, 28);
|
||||
assertTrue(false == calendar.isLeapYear(calendar.YEAR));
|
||||
assertTrue(52 == calendar.getWeeksInWeekYear());
|
||||
assertTrue(2018 == calendar.getWeekYear());
|
||||
assertTrue(30 == calendar.getActualMaximum(calendar.DAY_OF_MONTH));
|
||||
assertTrue(1 == calendar.getActualMinimum(calendar.DAY_OF_MONTH));
|
||||
assertTrue(1 == calendar.getGreatestMinimum(calendar.DAY_OF_MONTH));
|
||||
assertTrue(28 == calendar.getLeastMaximum(calendar.DAY_OF_MONTH));
|
||||
assertTrue(31 == calendar.getMaximum(calendar.DAY_OF_MONTH));
|
||||
assertTrue(1 == calendar.getMinimum(calendar.DAY_OF_MONTH));
|
||||
assertTrue(52 == calendar.getWeeksInWeekYear());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_Compare_Date_FirstDate_Greater_SecondDate() {
|
||||
GregorianCalendar firstDate = new GregorianCalendar(2018, 6, 28);
|
||||
GregorianCalendar secondDate = new GregorianCalendar(2018, 5, 28);
|
||||
assertTrue(1 == firstDate.compareTo(secondDate));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void test_Compare_Date_FirstDate_Smaller_SecondDate() {
|
||||
GregorianCalendar firstDate = new GregorianCalendar(2018, 5, 28);
|
||||
GregorianCalendar secondDate = new GregorianCalendar(2018, 6, 28);
|
||||
assertTrue(-1 == firstDate.compareTo(secondDate));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_Compare_Date_Both_Dates_Equal() {
|
||||
GregorianCalendar firstDate = new GregorianCalendar(2018, 6, 28);
|
||||
GregorianCalendar secondDate = new GregorianCalendar(2018, 6, 28);
|
||||
assertTrue(0 == firstDate.compareTo(secondDate));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_date_format() {
|
||||
GregorianCalendarExample calendarDemo = new GregorianCalendarExample();
|
||||
GregorianCalendar calendar = new GregorianCalendar(2018, 6, 28);
|
||||
assertEquals("28 Jul 2018", calendarDemo.formatDate(calendar));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_dateFormatdMMMuuuu() {
|
||||
String expectedDate = new GregorianCalendar(2018, 6, 28).toZonedDateTime()
|
||||
.format(DateTimeFormatter.ofPattern("d MMM uuuu"));
|
||||
assertEquals("28 Jul 2018", expectedDate);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_addDays() {
|
||||
GregorianCalendarExample calendarDemo = new GregorianCalendarExample();
|
||||
GregorianCalendar calendarActual = new GregorianCalendar(2018, 6, 28);
|
||||
GregorianCalendar calendarExpected = new GregorianCalendar(2018, 6, 28);
|
||||
calendarExpected.add(Calendar.DATE, 1);
|
||||
Date expectedDate = calendarExpected.getTime();
|
||||
assertEquals(expectedDate, calendarDemo.addDays(calendarActual, 1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_whenAddOneDay_thenMonthIsChanged() {
|
||||
final int finalDay1 = 1;
|
||||
final int finalMonthJul = 6;
|
||||
GregorianCalendar calendarExpected = new GregorianCalendar(2018, 5, 30);
|
||||
calendarExpected.add(Calendar.DATE, 1);
|
||||
System.out.println(calendarExpected.getTime());
|
||||
assertEquals(calendarExpected.get(Calendar.DATE), finalDay1);
|
||||
assertEquals(calendarExpected.get(Calendar.MONTH), finalMonthJul);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_whenSubtractOneDay_thenMonthIsChanged() {
|
||||
final int finalDay31 = 31;
|
||||
final int finalMonthMay = 4;
|
||||
GregorianCalendar calendarExpected = new GregorianCalendar(2018, 5, 1);
|
||||
calendarExpected.add(Calendar.DATE, -1);
|
||||
assertEquals(calendarExpected.get(Calendar.DATE), finalDay31);
|
||||
assertEquals(calendarExpected.get(Calendar.MONTH), finalMonthMay);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_subDays() {
|
||||
GregorianCalendarExample calendarDemo = new GregorianCalendarExample();
|
||||
GregorianCalendar calendarActual = new GregorianCalendar(2018, 6, 28);
|
||||
GregorianCalendar calendarExpected = new GregorianCalendar(2018, 6, 28);
|
||||
calendarExpected.add(Calendar.DATE, -1);
|
||||
Date expectedDate = calendarExpected.getTime();
|
||||
assertEquals(expectedDate, calendarDemo.subtractDays(calendarActual, 1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_rollAdd() {
|
||||
GregorianCalendarExample calendarDemo = new GregorianCalendarExample();
|
||||
GregorianCalendar calendarActual = new GregorianCalendar(2018, 6, 28);
|
||||
GregorianCalendar calendarExpected = new GregorianCalendar(2018, 6, 28);
|
||||
calendarExpected.roll(Calendar.MONTH, 8);
|
||||
Date expectedDate = calendarExpected.getTime();
|
||||
assertEquals(expectedDate, calendarDemo.rollAdd(calendarActual, 8));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_whenRollUpOneMonth_thenYearIsUnchanged() {
|
||||
final int rolledUpMonthJuly = 7, orginalYear2018 = 2018;
|
||||
GregorianCalendar calendarExpected = new GregorianCalendar(2018, 6, 28);
|
||||
calendarExpected.roll(Calendar.MONTH, 1);
|
||||
assertEquals(calendarExpected.get(Calendar.MONTH), rolledUpMonthJuly);
|
||||
assertEquals(calendarExpected.get(Calendar.YEAR), orginalYear2018);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_whenRollDownOneMonth_thenYearIsUnchanged() {
|
||||
final int rolledDownMonthJune = 5, orginalYear2018 = 2018;
|
||||
GregorianCalendar calendarExpected = new GregorianCalendar(2018, 6, 28);
|
||||
calendarExpected.roll(Calendar.MONTH, -1);
|
||||
assertEquals(calendarExpected.get(Calendar.MONTH), rolledDownMonthJune);
|
||||
assertEquals(calendarExpected.get(Calendar.YEAR), orginalYear2018);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_rollSubtract() {
|
||||
GregorianCalendarExample calendarDemo = new GregorianCalendarExample();
|
||||
GregorianCalendar calendarActual = new GregorianCalendar(2018, 6, 28);
|
||||
GregorianCalendar calendarExpected = new GregorianCalendar(2018, 6, 28);
|
||||
calendarExpected.roll(Calendar.MONTH, -8);
|
||||
Date expectedDate = calendarExpected.getTime();
|
||||
assertEquals(expectedDate, calendarDemo.rollAdd(calendarActual, -8));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_setMonth() {
|
||||
GregorianCalendarExample calendarDemo = new GregorianCalendarExample();
|
||||
GregorianCalendar calendarActual = new GregorianCalendar(2018, 6, 28);
|
||||
GregorianCalendar calendarExpected = new GregorianCalendar(2018, 6, 28);
|
||||
calendarExpected.set(Calendar.MONTH, 3);
|
||||
Date expectedDate = calendarExpected.getTime();
|
||||
assertEquals(expectedDate, calendarDemo.setMonth(calendarActual, 3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_setMonthApril() {
|
||||
final int setMonthApril = 3, orginalYear2018 = 2018, originalDate28 = 28;
|
||||
GregorianCalendar calendarExpected = new GregorianCalendar(2018, 6, 28);
|
||||
calendarExpected.set(Calendar.MONTH, 3);
|
||||
assertEquals(calendarExpected.get(Calendar.MONTH), setMonthApril);
|
||||
assertEquals(calendarExpected.get(Calendar.YEAR), orginalYear2018);
|
||||
assertEquals(calendarExpected.get(Calendar.DATE), originalDate28);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_toXMLGregorianCalendar() throws DatatypeConfigurationException {
|
||||
GregorianCalendarExample calendarDemo = new GregorianCalendarExample();
|
||||
DatatypeFactory datatypeFactory = DatatypeFactory.newInstance();
|
||||
GregorianCalendar calendarActual = new GregorianCalendar(2018, 6, 28);
|
||||
GregorianCalendar calendarExpected = new GregorianCalendar(2018, 6, 28);
|
||||
XMLGregorianCalendar expectedXMLGregorianCalendar = datatypeFactory
|
||||
.newXMLGregorianCalendar(calendarExpected);
|
||||
assertEquals(expectedXMLGregorianCalendar,
|
||||
calendarDemo.toXMLGregorianCalendar(calendarActual));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_isLeapYear_True() {
|
||||
GregorianCalendarExample calendarDemo = new GregorianCalendarExample();
|
||||
assertEquals(true, calendarDemo.isLeapYearExample(2016));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_isLeapYear_False() {
|
||||
GregorianCalendarExample calendarDemo = new GregorianCalendarExample();
|
||||
assertEquals(false, calendarDemo.isLeapYearExample(2018));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_toDate() throws DatatypeConfigurationException {
|
||||
GregorianCalendar calendarActual = new GregorianCalendar(2018, 6, 28);
|
||||
DatatypeFactory datatypeFactory = DatatypeFactory.newInstance();
|
||||
XMLGregorianCalendar expectedXMLGregorianCalendar = datatypeFactory
|
||||
.newXMLGregorianCalendar(calendarActual);
|
||||
expectedXMLGregorianCalendar.toGregorianCalendar().getTime();
|
||||
assertEquals(calendarActual.getTime(),
|
||||
expectedXMLGregorianCalendar.toGregorianCalendar().getTime() );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package com.baeldung.java9.time;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import org.junit.Test;
|
||||
|
||||
public class TimeApiUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenGetDatesBetweenWithUsingJava7_WhenStartEndDate_thenDatesList() {
|
||||
Date startDate = Calendar.getInstance().getTime();
|
||||
Calendar endCalendar = Calendar.getInstance();
|
||||
endCalendar.add(Calendar.DATE, 2);
|
||||
Date endDate = endCalendar.getTime();
|
||||
|
||||
List<Date> dates = TimeApi.getDatesBetweenUsingJava7(startDate, endDate);
|
||||
assertEquals(dates.size(), 2);
|
||||
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
Date date1 = calendar.getTime();
|
||||
assertEquals(dates.get(0).getDay(), date1.getDay());
|
||||
assertEquals(dates.get(0).getMonth(), date1.getMonth());
|
||||
assertEquals(dates.get(0).getYear(), date1.getYear());
|
||||
|
||||
calendar.add(Calendar.DATE, 1);
|
||||
Date date2 = calendar.getTime();
|
||||
assertEquals(dates.get(1).getDay(), date2.getDay());
|
||||
assertEquals(dates.get(1).getMonth(), date2.getMonth());
|
||||
assertEquals(dates.get(1).getYear(), date2.getYear());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenGetDatesBetweenWithUsingJava8_WhenStartEndDate_thenDatesList() {
|
||||
LocalDate startDate = LocalDate.now();
|
||||
LocalDate endDate = LocalDate.now().plusDays(2);
|
||||
|
||||
List<LocalDate> dates = TimeApi.getDatesBetweenUsingJava8(startDate, endDate);
|
||||
assertEquals(dates.size(), 2);
|
||||
assertEquals(dates.get(0), LocalDate.now());
|
||||
assertEquals(dates.get(1), LocalDate.now().plusDays(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenGetDatesBetweenWithUsingJava9_WhenStartEndDate_thenDatesList() {
|
||||
LocalDate startDate = LocalDate.now();
|
||||
LocalDate endDate = LocalDate.now().plusDays(2);
|
||||
|
||||
List<LocalDate> dates = TimeApi.getDatesBetweenUsingJava9(startDate, endDate);
|
||||
assertEquals(dates.size(), 2);
|
||||
assertEquals(dates.get(0), LocalDate.now());
|
||||
assertEquals(dates.get(1), LocalDate.now().plusDays(1));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
package com.baeldung.jodatime;
|
||||
|
||||
import org.joda.time.*;
|
||||
import org.joda.time.format.DateTimeFormat;
|
||||
import org.joda.time.format.DateTimeFormatter;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Date;
|
||||
import java.util.TimeZone;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class JodaTimeUnitTest {
|
||||
|
||||
@Test
|
||||
public void testDateTimeRepresentation() {
|
||||
|
||||
DateTimeZone.setDefault(DateTimeZone.forID("Europe/Bucharest"));
|
||||
|
||||
// representing current date and time
|
||||
LocalDate currentDate = LocalDate.now();
|
||||
LocalTime currentTime = LocalTime.now();
|
||||
LocalDateTime currentLocalDateTime = LocalDateTime.now();
|
||||
|
||||
LocalDateTime currentDateTimeFromJavaDate = new LocalDateTime(new Date());
|
||||
Date currentJavaDate = currentDateTimeFromJavaDate.toDate();
|
||||
|
||||
// representing custom date and time
|
||||
Date oneMinuteAgoDate = new Date(System.currentTimeMillis() - (60 * 1000));
|
||||
Instant oneMinutesAgoInstant = new Instant(oneMinuteAgoDate);
|
||||
|
||||
DateTime customDateTimeFromInstant = new DateTime(oneMinutesAgoInstant);
|
||||
DateTime customDateTimeFromJavaDate = new DateTime(oneMinuteAgoDate);
|
||||
DateTime customDateTimeFromString = new DateTime("2018-05-05T10:11:12.123");
|
||||
DateTime customDateTimeFromParts = new DateTime(2018, 5, 5, 10, 11, 12, 123);
|
||||
|
||||
// parsing
|
||||
DateTime parsedDateTime = DateTime.parse("2018-05-05T10:11:12.123");
|
||||
assertEquals("2018-05-05T10:11:12.123+03:00", parsedDateTime.toString());
|
||||
|
||||
DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("MM/dd/yyyy HH:mm:ss");
|
||||
DateTime parsedDateTimeUsingFormatter = DateTime.parse("05/05/2018 10:11:12", dateTimeFormatter);
|
||||
assertEquals("2018-05-05T10:11:12.000+03:00", parsedDateTimeUsingFormatter.toString());
|
||||
|
||||
// Instant
|
||||
Instant instant = new Instant();
|
||||
Instant.now();
|
||||
|
||||
Instant instantFromString = new Instant("2018-05-05T10:11:12");
|
||||
Instant instantFromDate = new Instant(oneMinuteAgoDate);
|
||||
Instant instantFromTimestamp = new Instant(System.currentTimeMillis() - (60 * 1000));
|
||||
Instant parsedInstant = Instant.parse("05/05/2018 10:11:12", dateTimeFormatter);
|
||||
|
||||
Instant instantNow = Instant.now();
|
||||
Instant oneMinuteAgoInstant = new Instant(oneMinuteAgoDate);
|
||||
|
||||
// epochMilli and epochSecond
|
||||
long milliesFromEpochTime = System.currentTimeMillis();
|
||||
long secondsFromEpochTime = milliesFromEpochTime / 1000;
|
||||
Instant instantFromEpochMilli = Instant.ofEpochMilli(milliesFromEpochTime);
|
||||
Instant instantFromEpocSeconds = Instant.ofEpochSecond(secondsFromEpochTime);
|
||||
|
||||
// convert Instants
|
||||
DateTime dateTimeFromInstant = instant.toDateTime();
|
||||
Date javaDateFromInstant = instant.toDate();
|
||||
|
||||
int year = instant.get(DateTimeFieldType.year());
|
||||
int month = instant.get(DateTimeFieldType.monthOfYear());
|
||||
int day = instant.get(DateTimeFieldType.dayOfMonth());
|
||||
int hour = instant.get(DateTimeFieldType.hourOfDay());
|
||||
|
||||
// Duration, Period, Instant
|
||||
long currentTimestamp = System.currentTimeMillis();
|
||||
long oneHourAgo = currentTimestamp - 24*60*1000;
|
||||
|
||||
Duration duration = new Duration(oneHourAgo, currentTimestamp);
|
||||
Instant.now().plus(duration);
|
||||
|
||||
long durationInDays = duration.getStandardDays();
|
||||
long durationInHours = duration.getStandardHours();
|
||||
long durationInMinutes = duration.getStandardMinutes();
|
||||
long durationInSeconds = duration.getStandardSeconds();
|
||||
long durationInMilli = duration.getMillis();
|
||||
|
||||
// converting between classes
|
||||
DateTimeUtils.setCurrentMillisFixed(currentTimestamp);
|
||||
LocalDateTime currentDateAndTime = LocalDateTime.now();
|
||||
|
||||
assertEquals(new DateTime(currentTimestamp), currentDateAndTime.toDateTime());
|
||||
assertEquals(new LocalDate(currentTimestamp), currentDateAndTime.toLocalDate());
|
||||
assertEquals(new LocalTime(currentTimestamp), currentDateAndTime.toLocalTime());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testJodaInstant() {
|
||||
|
||||
Date oneMinuteAgoDate = new Date(System.currentTimeMillis() - (60 * 1000));
|
||||
|
||||
Instant instantNow = Instant.now();
|
||||
Instant oneMinuteAgoInstant = new Instant(oneMinuteAgoDate);
|
||||
|
||||
assertTrue(instantNow.compareTo(oneMinuteAgoInstant) > 0);
|
||||
assertTrue(instantNow.isAfter(oneMinuteAgoInstant));
|
||||
assertTrue(oneMinuteAgoInstant.isBefore(instantNow));
|
||||
assertTrue(oneMinuteAgoInstant.isBeforeNow());
|
||||
assertFalse(oneMinuteAgoInstant.isEqual(instantNow));
|
||||
|
||||
LocalDateTime localDateTime = new LocalDateTime("2018-02-01");
|
||||
Period period = new Period().withMonths(1);
|
||||
LocalDateTime datePlusPeriod = localDateTime.plus(period);
|
||||
|
||||
Instant startInterval1 = new Instant("2018-05-05T09:00:00.000");
|
||||
Instant endInterval1 = new Instant("2018-05-05T11:00:00.000");
|
||||
Interval interval1 = new Interval(startInterval1, endInterval1);
|
||||
|
||||
Instant startInterval2 = new Instant("2018-05-05T10:00:00.000");
|
||||
Instant endInterval2 = new Instant("2018-05-05T11:00:00.000");
|
||||
Interval interval2 = new Interval(startInterval2, endInterval2);
|
||||
|
||||
Instant startInterval3 = new Instant("2018-05-05T11:00:00.000");
|
||||
Instant endInterval3 = new Instant("2018-05-05T13:00:00.000");
|
||||
Interval interval3 = new Interval(startInterval3, endInterval3);
|
||||
|
||||
Interval overlappingInterval = interval1.overlap(interval2);
|
||||
Interval notOverlappingInterval = interval1.overlap(interval3);
|
||||
|
||||
assertTrue(overlappingInterval.isEqual(new Interval(new Instant("2018-05-05T10:00:00.000"), new Instant("2018-05-05T11:00:00.000"))));
|
||||
assertNotNull(overlappingInterval);
|
||||
|
||||
interval1.abuts(interval3);
|
||||
assertTrue(interval1.abuts(new Interval(new Instant("2018-05-05T11:00:00.000"), new Instant("2018-05-05T13:00:00.000"))));
|
||||
|
||||
interval1.gap(interval2);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void testDateTimeOperations() {
|
||||
|
||||
DateTimeUtils.setCurrentMillisFixed(1529612783288L);
|
||||
DateTimeZone.setDefault(DateTimeZone.UTC);
|
||||
|
||||
LocalDateTime currentLocalDateTime = LocalDateTime.now();
|
||||
assertEquals("2018-06-21T20:26:23.288", currentLocalDateTime.toString());
|
||||
|
||||
LocalDateTime nextDayDateTime = currentLocalDateTime.plusDays(1);
|
||||
assertEquals("2018-06-22T20:26:23.288", nextDayDateTime.toString());
|
||||
|
||||
Period oneMonth = new Period().withMonths(1);
|
||||
LocalDateTime nextMonthDateTime = currentLocalDateTime.plus(oneMonth);
|
||||
assertEquals("2018-07-21T20:26:23.288", nextMonthDateTime.toString());
|
||||
|
||||
LocalDateTime previousDayLocalDateTime = currentLocalDateTime.minusDays(1);
|
||||
assertEquals("2018-06-20T20:26:23.288", previousDayLocalDateTime.toString());
|
||||
|
||||
LocalDateTime currentDateAtHour10 = currentLocalDateTime
|
||||
.withHourOfDay(0)
|
||||
.withMinuteOfHour(0)
|
||||
.withSecondOfMinute(0)
|
||||
.withMillisOfSecond(0);
|
||||
assertEquals("2018-06-21T00:00:00.000", currentDateAtHour10.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testTimezones() {
|
||||
|
||||
System.getProperty("user.timezone");
|
||||
DateTimeZone.getAvailableIDs();
|
||||
// DateTimeZone.setDefault(DateTimeZone.forID("Europe/Bucharest"));
|
||||
|
||||
DateTimeUtils.setCurrentMillisFixed(1529612783288L);
|
||||
|
||||
DateTime dateTimeInChicago = new DateTime(DateTimeZone.forID("America/Chicago"));
|
||||
assertEquals("2018-06-21T15:26:23.288-05:00", dateTimeInChicago.toString());
|
||||
|
||||
DateTime dateTimeInBucharest = new DateTime(DateTimeZone.forID("Europe/Bucharest"));
|
||||
assertEquals("2018-06-21T23:26:23.288+03:00", dateTimeInBucharest.toString());
|
||||
|
||||
LocalDateTime localDateTimeInChicago = new LocalDateTime(DateTimeZone.forID("America/Chicago"));
|
||||
assertEquals("2018-06-21T15:26:23.288", localDateTimeInChicago.toString());
|
||||
|
||||
DateTime convertedDateTime = localDateTimeInChicago.toDateTime(DateTimeZone.forID("Europe/Bucharest"));
|
||||
assertEquals("2018-06-21T15:26:23.288+03:00", convertedDateTime.toString());
|
||||
}
|
||||
|
||||
}
|
||||
15
core-java-modules/core-java-datetime-java8/README.md
Normal file
15
core-java-modules/core-java-datetime-java8/README.md
Normal file
@@ -0,0 +1,15 @@
|
||||
## Java 8+ Date and Time API
|
||||
|
||||
This module contains articles about the Date and Time API introduced with Java 8.
|
||||
|
||||
### Relevant Articles:
|
||||
- [Introduction to the Java 8 Date/Time API](http://www.baeldung.com/java-8-date-time-intro)
|
||||
- [Migrating to the New Java 8 Date Time API](http://www.baeldung.com/migrating-to-java-8-date-time-api)
|
||||
- [Get the Current Date, Time and Timestamp in Java 8](http://www.baeldung.com/current-date-time-and-timestamp-in-java-8)
|
||||
- [TemporalAdjuster in Java](http://www.baeldung.com/java-temporal-adjuster)
|
||||
- [ZoneOffset in Java](https://www.baeldung.com/java-zone-offset)
|
||||
- [Differences Between ZonedDateTime and OffsetDateTime](https://www.baeldung.com/java-zoneddatetime-offsetdatetime)
|
||||
- [Period and Duration in Java](http://www.baeldung.com/java-period-duration)
|
||||
- [How to Get the Start and the End of a Day using Java](http://www.baeldung.com/java-day-start-end)
|
||||
- [Set the Time Zone of a Date in Java](https://www.baeldung.com/java-set-date-time-zone)
|
||||
- [Comparing Dates in Java](https://www.baeldung.com/java-comparing-dates)
|
||||
70
core-java-modules/core-java-datetime-java8/pom.xml
Normal file
70
core-java-modules/core-java-datetime-java8/pom.xml
Normal file
@@ -0,0 +1,70 @@
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>core-java-datetime-java8</artifactId>
|
||||
<version>${project.parent.version}</version>
|
||||
<name>core-java-datetime-java8</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-java</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../../parent-java</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang3.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>joda-time</groupId>
|
||||
<artifactId>joda-time</artifactId>
|
||||
<version>${joda-time.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>log4j</groupId>
|
||||
<artifactId>log4j</artifactId>
|
||||
<version>${log4j.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>core-java-datetime-java8</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>${maven.compiler.source}</source>
|
||||
<target>${maven.compiler.target}</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<maven.compiler.source>1.9</maven.compiler.source>
|
||||
<maven.compiler.target>1.9</maven.compiler.target>
|
||||
<joda-time.version>2.10</joda-time.version>
|
||||
<!-- testing -->
|
||||
<assertj.version>3.6.1</assertj.version>
|
||||
</properties>
|
||||
</project>
|
||||
@@ -0,0 +1,35 @@
|
||||
package com.baeldung.date.comparison;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.time.ZonedDateTime;
|
||||
|
||||
import static java.time.temporal.ChronoUnit.*;
|
||||
|
||||
public class DateTimeComparisonUtils {
|
||||
|
||||
public static boolean isSameDay(LocalDateTime timestamp, LocalDate localDateToCompare) {
|
||||
return timestamp.toLocalDate().isEqual(localDateToCompare);
|
||||
}
|
||||
|
||||
public static boolean isSameDay(LocalDateTime timestamp, LocalDateTime timestampToCompare) {
|
||||
return timestamp.truncatedTo(DAYS).isEqual(timestampToCompare.truncatedTo(DAYS));
|
||||
}
|
||||
|
||||
public static boolean isSameHour(LocalDateTime timestamp, LocalDateTime timestampToCompare) {
|
||||
return timestamp.truncatedTo(HOURS).isEqual(timestampToCompare.truncatedTo(HOURS));
|
||||
}
|
||||
|
||||
public static boolean isSameMinute(LocalDateTime timestamp, LocalDateTime timestampToCompare) {
|
||||
return timestamp.truncatedTo(MINUTES).isEqual(timestampToCompare.truncatedTo(MINUTES));
|
||||
}
|
||||
|
||||
public static boolean isSameHour(ZonedDateTime zonedTimestamp, ZonedDateTime zonedTimestampToCompare) {
|
||||
return zonedTimestamp.truncatedTo(HOURS).isEqual(zonedTimestampToCompare.truncatedTo(HOURS));
|
||||
}
|
||||
|
||||
public static boolean isSameHour(ZonedDateTime zonedDateTime, LocalDateTime localDateTime, ZoneId zoneId) {
|
||||
return isSameHour(zonedDateTime, localDateTime.atZone(zoneId));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.baeldung.date.comparison;
|
||||
|
||||
import org.apache.commons.lang3.time.DateUtils;
|
||||
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
|
||||
public class LegacyDateComparisonUtils {
|
||||
|
||||
public static boolean isSameDay(Date date, Date dateToCompare) {
|
||||
return DateUtils.isSameDay(date, dateToCompare);
|
||||
}
|
||||
|
||||
public static boolean isSameHour(Date date, Date dateToCompare) {
|
||||
return DateUtils.truncatedEquals(date, dateToCompare, Calendar.HOUR);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.baeldung.datetime;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.LocalTime;
|
||||
|
||||
public class UseDuration {
|
||||
|
||||
public LocalTime modifyDates(LocalTime localTime, Duration duration) {
|
||||
return localTime.plus(duration);
|
||||
}
|
||||
|
||||
public Duration getDifferenceBetweenDates(LocalTime localTime1, LocalTime localTime2) {
|
||||
return Duration.between(localTime1, localTime2);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package com.baeldung.datetime;
|
||||
|
||||
import java.time.DayOfWeek;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.LocalTime;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.time.temporal.TemporalAdjusters;
|
||||
|
||||
class UseLocalDate {
|
||||
|
||||
LocalDate getLocalDateUsingFactoryOfMethod(int year, int month, int dayOfMonth) {
|
||||
return LocalDate.of(year, month, dayOfMonth);
|
||||
}
|
||||
|
||||
LocalDate getLocalDateUsingParseMethod(String representation) {
|
||||
return LocalDate.parse(representation);
|
||||
}
|
||||
|
||||
LocalDate getLocalDateFromClock() {
|
||||
LocalDate localDate = LocalDate.now();
|
||||
return localDate;
|
||||
}
|
||||
|
||||
LocalDate getNextDay(LocalDate localDate) {
|
||||
return localDate.plusDays(1);
|
||||
}
|
||||
|
||||
LocalDate getPreviousDay(LocalDate localDate) {
|
||||
return localDate.minus(1, ChronoUnit.DAYS);
|
||||
}
|
||||
|
||||
DayOfWeek getDayOfWeek(LocalDate localDate) {
|
||||
DayOfWeek day = localDate.getDayOfWeek();
|
||||
return day;
|
||||
}
|
||||
|
||||
LocalDate getFirstDayOfMonth() {
|
||||
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;
|
||||
}
|
||||
|
||||
LocalDateTime getStartOfDayOfLocalDate(LocalDate localDate) {
|
||||
LocalDateTime startofDay = LocalDateTime.of(localDate, LocalTime.MIDNIGHT);
|
||||
return startofDay;
|
||||
}
|
||||
|
||||
LocalDateTime getStartOfDayAtMinTime(LocalDate localDate) {
|
||||
LocalDateTime startofDay = localDate.atTime(LocalTime.MIN);
|
||||
return startofDay;
|
||||
}
|
||||
|
||||
LocalDateTime getStartOfDayAtMidnightTime(LocalDate localDate) {
|
||||
LocalDateTime startofDay = localDate.atTime(LocalTime.MIDNIGHT);
|
||||
return startofDay;
|
||||
}
|
||||
|
||||
LocalDateTime getEndOfDay(LocalDate localDate) {
|
||||
LocalDateTime endOfDay = localDate.atTime(LocalTime.MAX);
|
||||
return endOfDay;
|
||||
}
|
||||
|
||||
LocalDateTime getEndOfDayFromLocalTime(LocalDate localDate) {
|
||||
LocalDateTime endOfDate = LocalTime.MAX.atDate(localDate);
|
||||
return endOfDate;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.baeldung.datetime;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.LocalTime;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.temporal.ChronoField;
|
||||
|
||||
public class UseLocalDateTime {
|
||||
|
||||
public LocalDateTime getLocalDateTimeUsingParseMethod(String representation) {
|
||||
return LocalDateTime.parse(representation);
|
||||
}
|
||||
|
||||
LocalDateTime getEndOfDayFromLocalDateTimeDirectly(LocalDateTime localDateTime) {
|
||||
LocalDateTime endOfDate = localDateTime.with(ChronoField.NANO_OF_DAY, LocalTime.MAX.toNanoOfDay());
|
||||
return endOfDate;
|
||||
}
|
||||
|
||||
LocalDateTime getEndOfDayFromLocalDateTime(LocalDateTime localDateTime) {
|
||||
LocalDateTime endOfDate = localDateTime.toLocalDate()
|
||||
.atTime(LocalTime.MAX);
|
||||
return endOfDate;
|
||||
}
|
||||
|
||||
LocalDateTime ofEpochSecond(int epochSecond, ZoneOffset zoneOffset) {
|
||||
return LocalDateTime.ofEpochSecond(epochSecond, 0, zoneOffset);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package com.baeldung.datetime;
|
||||
|
||||
import java.time.LocalTime;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
|
||||
public class UseLocalTime {
|
||||
|
||||
LocalTime getLocalTimeUsingFactoryOfMethod(int hour, int min, int seconds) {
|
||||
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);
|
||||
}
|
||||
|
||||
private LocalTime getLocalTimeFromClock() {
|
||||
return LocalTime.now();
|
||||
}
|
||||
|
||||
LocalTime addAnHour(LocalTime localTime) {
|
||||
return localTime.plus(1, ChronoUnit.HOURS);
|
||||
}
|
||||
|
||||
int getHourFromLocalTime(LocalTime localTime) {
|
||||
return localTime.getHour();
|
||||
}
|
||||
|
||||
LocalTime getLocalTimeWithMinuteSetToValue(LocalTime localTime, int minute) {
|
||||
return localTime.withMinute(minute);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.baeldung.datetime;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.Period;
|
||||
|
||||
class UsePeriod {
|
||||
|
||||
LocalDate modifyDates(LocalDate localDate, Period period) {
|
||||
return localDate.plus(period);
|
||||
}
|
||||
|
||||
Period getDifferenceBetweenDates(LocalDate localDate1, LocalDate localDate2) {
|
||||
return Period.between(localDate1, localDate2);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.baeldung.datetime;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
|
||||
public class UseToInstant {
|
||||
|
||||
public LocalDateTime convertDateToLocalDate(Date date) {
|
||||
return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
|
||||
}
|
||||
|
||||
public LocalDateTime convertDateToLocalDate(Calendar calendar) {
|
||||
return LocalDateTime.ofInstant(calendar.toInstant(), ZoneId.systemDefault());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.baeldung.datetime;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.time.temporal.ChronoField;
|
||||
|
||||
class UseZonedDateTime {
|
||||
|
||||
ZonedDateTime getZonedDateTime(LocalDateTime localDateTime, ZoneId zoneId) {
|
||||
return ZonedDateTime.of(localDateTime, zoneId);
|
||||
}
|
||||
|
||||
ZonedDateTime getZonedDateTimeUsingParseMethod(String parsableString) {
|
||||
return ZonedDateTime.parse(parsableString);
|
||||
}
|
||||
|
||||
ZonedDateTime getStartOfDay(LocalDate localDate, ZoneId zone) {
|
||||
ZonedDateTime startOfDay = localDate.atStartOfDay()
|
||||
.atZone(zone);
|
||||
return startOfDay;
|
||||
}
|
||||
|
||||
ZonedDateTime getStartOfDayShorthand(LocalDate localDate, ZoneId zone) {
|
||||
ZonedDateTime startOfDay = localDate.atStartOfDay(zone);
|
||||
return startOfDay;
|
||||
}
|
||||
|
||||
ZonedDateTime getStartOfDayFromZonedDateTime(ZonedDateTime zonedDateTime) {
|
||||
ZonedDateTime startOfDay = zonedDateTime.toLocalDateTime()
|
||||
.toLocalDate()
|
||||
.atStartOfDay(zonedDateTime.getZone());
|
||||
return startOfDay;
|
||||
}
|
||||
|
||||
ZonedDateTime getStartOfDayAtMinTime(ZonedDateTime zonedDateTime) {
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.baeldung.temporaladjuster;
|
||||
|
||||
import java.time.DayOfWeek;
|
||||
import java.time.temporal.ChronoField;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.time.temporal.Temporal;
|
||||
import java.time.temporal.TemporalAdjuster;
|
||||
|
||||
public class CustomTemporalAdjuster implements TemporalAdjuster {
|
||||
|
||||
@Override
|
||||
public Temporal adjustInto(Temporal temporal) {
|
||||
switch (DayOfWeek.of(temporal.get(ChronoField.DAY_OF_WEEK))) {
|
||||
case FRIDAY:
|
||||
return temporal.plus(3, ChronoUnit.DAYS);
|
||||
case SATURDAY:
|
||||
return temporal.plus(2, ChronoUnit.DAYS);
|
||||
default:
|
||||
return temporal.plus(1, ChronoUnit.DAYS);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package com.baeldung.date.comparison;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.time.ZonedDateTime;
|
||||
|
||||
import static org.hamcrest.Matchers.is;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
class DateTimeComparisonUtilsUnitTest {
|
||||
|
||||
@Test
|
||||
void givenLocalDateTimes_whenIsSameDay_thenCompareTrue() {
|
||||
LocalDateTime firstTimestamp = LocalDateTime.of(2019, 8, 10, 11, 00, 0);
|
||||
LocalDateTime secondTimestamp = firstTimestamp.plusHours(5);
|
||||
LocalDateTime thirdTimestamp = firstTimestamp.plusDays(1);
|
||||
|
||||
assertThat(DateTimeComparisonUtils.isSameDay(firstTimestamp, secondTimestamp), is(true));
|
||||
|
||||
assertThat(DateTimeComparisonUtils.isSameDay(secondTimestamp, thirdTimestamp), is(false));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenLocalDateAndLocalDateTime_whenIsSameDay_thenCompareTrue() {
|
||||
LocalDate localDate = LocalDate.of(2019, 8, 10);
|
||||
LocalDateTime localDateTime = LocalDateTime.of(2019, 8, 10, 11, 30, 0);
|
||||
|
||||
assertThat(DateTimeComparisonUtils.isSameDay(localDateTime, localDate), is(true));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenLocalDateTimes_whenIsSameHour_thenCompareTrue() {
|
||||
LocalDateTime firstTimestamp = LocalDateTime.of(2019, 8, 10, 8, 00, 0);
|
||||
LocalDateTime secondTimestamp = firstTimestamp.plusMinutes(15);
|
||||
LocalDateTime thirdTimestamp = firstTimestamp.plusHours(2);
|
||||
|
||||
assertThat(DateTimeComparisonUtils.isSameHour(firstTimestamp, secondTimestamp), is(true));
|
||||
|
||||
assertThat(DateTimeComparisonUtils.isSameHour(secondTimestamp, thirdTimestamp), is(false));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenLocalDateTimes_whenIsSameMinute_thenCompareTrue() {
|
||||
LocalDateTime firstTimestamp = LocalDateTime.of(2019, 8, 10, 8, 15, 0);
|
||||
LocalDateTime secondTimestamp = firstTimestamp.plusSeconds(30);
|
||||
LocalDateTime thirdTimestamp = firstTimestamp.plusMinutes(5);
|
||||
|
||||
assertThat(DateTimeComparisonUtils.isSameMinute(firstTimestamp, secondTimestamp), is(true));
|
||||
|
||||
assertThat(DateTimeComparisonUtils.isSameMinute(secondTimestamp, thirdTimestamp), is(false));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenZonedDateTimes_whenIsSameHour_thenCompareTrue() {
|
||||
ZonedDateTime zonedTimestamp = ZonedDateTime.of(2019, 8, 10, 8, 0, 0, 30,
|
||||
ZoneId.of("America/New_York"));
|
||||
ZonedDateTime zonedTimestampToCompare = ZonedDateTime.of(2019, 8, 10, 14, 0, 0, 0,
|
||||
ZoneId.of("Europe/Berlin"));
|
||||
|
||||
assertThat(DateTimeComparisonUtils.isSameHour(zonedTimestamp, zonedTimestampToCompare), is(true));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenZonedDateTimeAndLocalDateTime_whenIsSameHour_thenCompareTrue() {
|
||||
ZonedDateTime zonedTimestamp = ZonedDateTime.of(2019, 8, 10, 8, 15, 0, 0,
|
||||
ZoneId.of("America/New_York"));
|
||||
LocalDateTime localTimestamp = LocalDateTime.of(2019, 8, 10, 14, 20, 0);
|
||||
ZoneId zoneId = ZoneId.of("Europe/Berlin");
|
||||
|
||||
assertThat(DateTimeComparisonUtils.isSameHour(zonedTimestamp, localTimestamp, zoneId), is(true));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package com.baeldung.date.comparison;
|
||||
|
||||
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
|
||||
public void givenLocalDates_whenComparing_thenAssertsPass() {
|
||||
LocalDate firstDate = LocalDate.of(2019, 8, 10);
|
||||
LocalDate secondDate = LocalDate.of(2019, 7, 1);
|
||||
LocalDate thirdDate = LocalDate.of(2019, 7, 1); // same date as secondDate
|
||||
|
||||
assertThat(firstDate.isAfter(secondDate), is(true));
|
||||
assertThat(firstDate.isBefore(secondDate), is(false));
|
||||
|
||||
assertThat(firstDate.isEqual(secondDate), is(false));
|
||||
assertThat(firstDate.equals(secondDate), is(false));
|
||||
|
||||
assertThat(firstDate.compareTo(secondDate), is(1));
|
||||
assertThat(secondDate.compareTo(firstDate), is(-1));
|
||||
|
||||
assertThat(secondDate.isAfter(thirdDate), is(false));
|
||||
assertThat(secondDate.isBefore(thirdDate), is(false));
|
||||
assertThat(secondDate.isEqual(thirdDate), is(true));
|
||||
assertThat(secondDate.equals(thirdDate), is(true));
|
||||
assertThat(secondDate.compareTo(thirdDate), is(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLocalDateTimes_whenComparing_thenAssertsPass() {
|
||||
LocalDateTime firstTimestamp = LocalDateTime.of(2019, 8, 10, 11, 30, 0);
|
||||
LocalDateTime secondTimestamp = LocalDateTime.of(2019, 8, 10, 11, 15, 0);
|
||||
LocalDateTime thirdTimestamp = LocalDateTime.of(2019, 8, 10, 11, 15, 0); // same as secondTimestamp
|
||||
|
||||
assertThat(firstTimestamp.isAfter(secondTimestamp), is(true));
|
||||
assertThat(firstTimestamp.isBefore(secondTimestamp), is(false));
|
||||
|
||||
assertThat(firstTimestamp.isEqual(secondTimestamp), is(false));
|
||||
assertThat(firstTimestamp.equals(secondTimestamp), is(false));
|
||||
|
||||
assertThat(firstTimestamp.compareTo(secondTimestamp), is(1));
|
||||
assertThat(secondTimestamp.compareTo(firstTimestamp), is(-1));
|
||||
|
||||
assertThat(secondTimestamp.isAfter(thirdTimestamp), is(false));
|
||||
assertThat(secondTimestamp.isBefore(thirdTimestamp), is(false));
|
||||
assertThat(secondTimestamp.isEqual(thirdTimestamp), is(true));
|
||||
assertThat(secondTimestamp.compareTo(thirdTimestamp), is(0));
|
||||
}
|
||||
|
||||
@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"));
|
||||
|
||||
assertThat(timeInNewYork.isAfter(timeInBerlin), is(false));
|
||||
assertThat(timeInNewYork.isBefore(timeInBerlin), is(false));
|
||||
|
||||
assertThat(timeInNewYork.isEqual(timeInBerlin), is(true));
|
||||
assertThat(timeInNewYork.equals(timeInBerlin), is(false));
|
||||
|
||||
assertThat(timeInNewYork.compareTo(timeInBerlin), is(-1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLocalTimes_whenComparing_thenAssertsPass() {
|
||||
LocalTime firstTime = LocalTime.of(8, 30);
|
||||
LocalTime secondTime = LocalTime.of(9, 45);
|
||||
|
||||
assertThat(firstTime.isAfter(secondTime), is(false));
|
||||
assertThat(firstTime.isBefore(secondTime), is(true));
|
||||
|
||||
assertThat(firstTime.equals(secondTime), is(false));
|
||||
|
||||
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));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package com.baeldung.date.comparison;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.util.Date;
|
||||
|
||||
import static org.hamcrest.Matchers.is;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
class LegacyDateComparisonUtilsUnitTest {
|
||||
|
||||
private Date toDate(LocalDateTime localDateTime) {
|
||||
return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenDatesWithDifferentHours_whenIsSameDay_thenReturnsTrue() {
|
||||
Date firstDate = toDate(LocalDateTime.of(2019, 8, 10, 11, 00, 00));
|
||||
Date secondDate = toDate(LocalDateTime.of(2019, 8, 10, 12, 00, 00));
|
||||
Date thirdDate = toDate(LocalDateTime.of(2019, 8, 15, 12, 00, 00));
|
||||
|
||||
assertThat(LegacyDateComparisonUtils.isSameDay(firstDate, secondDate), is(true));
|
||||
assertThat(LegacyDateComparisonUtils.isSameDay(secondDate, thirdDate), is(false));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenDatesWithingSameHour_whenIsSameHour_thenReturnsTrue() {
|
||||
Date firstDate = toDate(LocalDateTime.of(2019, 8, 10, 11, 00, 00));
|
||||
Date secondDate = toDate(LocalDateTime.of(2019, 8, 10, 11, 15, 00));
|
||||
Date thirdDate = toDate(LocalDateTime.of(2019, 8, 10, 12, 00, 00));
|
||||
|
||||
assertThat(LegacyDateComparisonUtils.isSameHour(firstDate, secondDate), is(true));
|
||||
assertThat(LegacyDateComparisonUtils.isSameHour(secondDate, thirdDate), is(false));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenDates__whenComparing_thenAssertsPass() {
|
||||
Date firstDate = toDate(LocalDateTime.of(2019, 8, 10, 0, 00, 00));
|
||||
Date secondDate = toDate(LocalDateTime.of(2019, 8, 15, 0, 00, 00));
|
||||
Date thirdDate = toDate(LocalDateTime.of(2019, 8, 15, 0, 00, 00)); // same date as secondDate
|
||||
|
||||
assertThat(firstDate.after(secondDate), is(false));
|
||||
assertThat(firstDate.before(secondDate), is(true));
|
||||
assertThat(firstDate.compareTo(secondDate), is(-1));
|
||||
assertThat(firstDate.equals(secondDate), is(false));
|
||||
|
||||
assertThat(thirdDate.after(secondDate), is(false));
|
||||
assertThat(thirdDate.before(secondDate), is(false));
|
||||
assertThat(thirdDate.compareTo(secondDate), is(0));
|
||||
assertThat(thirdDate.equals(secondDate), is(true));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.baeldung.dateapi;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneId;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.util.Date;
|
||||
import java.util.GregorianCalendar;
|
||||
import java.util.TimeZone;
|
||||
|
||||
public class ConversionExample {
|
||||
public static void main(String[] args) {
|
||||
Instant instantFromCalendar = GregorianCalendar.getInstance().toInstant();
|
||||
ZonedDateTime zonedDateTimeFromCalendar = new GregorianCalendar().toZonedDateTime();
|
||||
Date dateFromInstant = Date.from(Instant.now());
|
||||
GregorianCalendar calendarFromZonedDateTime = GregorianCalendar.from(ZonedDateTime.now());
|
||||
Instant instantFromDate = new Date().toInstant();
|
||||
ZoneId zoneIdFromTimeZone = TimeZone.getTimeZone("PST").toZoneId();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
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");
|
||||
Instant end = Instant.parse("2017-10-03T10:16:30.00Z");
|
||||
|
||||
Duration duration = Duration.between(start, end);
|
||||
|
||||
assertFalse(duration.isNegative());
|
||||
|
||||
assertEquals(60, duration.getSeconds());
|
||||
assertEquals(1, duration.toMinutes());
|
||||
|
||||
Duration fromDays = Duration.ofDays(1);
|
||||
assertEquals(86400, fromDays.getSeconds());
|
||||
|
||||
Duration fromMinutes = Duration.ofMinutes(60);
|
||||
assertEquals(1, fromMinutes.toHours());
|
||||
|
||||
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());
|
||||
|
||||
Duration fromChar1 = Duration.parse("P1DT1H10M10.5S");
|
||||
Duration fromChar2 = Duration.parse("PT10M");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
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;
|
||||
|
||||
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() {
|
||||
|
||||
LocalDate startDate = LocalDate.of(2015, 2, 15);
|
||||
LocalDate endDate = LocalDate.of(2017, 1, 21);
|
||||
|
||||
Period period = Period.between(startDate, endDate);
|
||||
|
||||
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());
|
||||
|
||||
Period fromUnits = Period.of(3, 10, 10);
|
||||
Period fromDays = Period.ofDays(50);
|
||||
Period fromMonths = Period.ofMonths(5);
|
||||
Period fromYears = Period.ofYears(10);
|
||||
Period fromWeeks = Period.ofWeeks(40);
|
||||
|
||||
assertEquals(280, fromWeeks.getDays());
|
||||
|
||||
Period fromCharYears = Period.parse("P2Y");
|
||||
assertEquals(2, fromCharYears.getYears());
|
||||
Period fromCharUnits = Period.parse("P2Y3M5D");
|
||||
assertEquals(5, fromCharUnits.getDays());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
package com.baeldung.dateapi;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.text.ParseException;
|
||||
import java.time.Duration;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.LocalTime;
|
||||
import java.time.Month;
|
||||
import java.time.YearMonth;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class JavaUtilTimeUnitTest {
|
||||
|
||||
@Test
|
||||
public void currentTime() {
|
||||
final LocalDate now = LocalDate.now();
|
||||
|
||||
System.out.println(now);
|
||||
// there is not much to test here
|
||||
}
|
||||
|
||||
@Test
|
||||
public void specificTime() {
|
||||
LocalDate birthDay = LocalDate.of(1990, Month.DECEMBER, 15);
|
||||
|
||||
System.out.println(birthDay);
|
||||
// there is not much to test here
|
||||
}
|
||||
|
||||
@Test
|
||||
public void extractMonth() {
|
||||
Month month = LocalDate.of(1990, Month.DECEMBER, 15).getMonth();
|
||||
|
||||
assertThat(month).isEqualTo(Month.DECEMBER);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void subtractTime() {
|
||||
LocalDateTime fiveHoursBefore = LocalDateTime.of(1990, Month.DECEMBER, 15, 15, 0).minusHours(5);
|
||||
|
||||
assertThat(fiveHoursBefore.getHour()).isEqualTo(10);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void alterField() {
|
||||
LocalDateTime inJune = LocalDateTime.of(1990, Month.DECEMBER, 15, 15, 0).with(Month.JUNE);
|
||||
|
||||
assertThat(inJune.getMonth()).isEqualTo(Month.JUNE);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void truncate() {
|
||||
LocalTime truncated = LocalTime.of(15, 12, 34).truncatedTo(ChronoUnit.HOURS);
|
||||
|
||||
assertThat(truncated).isEqualTo(LocalTime.of(15, 0, 0));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getTimeSpan() {
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
LocalDateTime hourLater = now.plusHours(1);
|
||||
Duration span = Duration.between(now, hourLater);
|
||||
|
||||
assertThat(span).isEqualTo(Duration.ofHours(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void formatAndParse() throws ParseException {
|
||||
LocalDate someDate = LocalDate.of(2016, 12, 7);
|
||||
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
|
||||
String formattedDate = someDate.format(formatter);
|
||||
LocalDate parsedDate = LocalDate.parse(formattedDate, formatter);
|
||||
|
||||
assertThat(formattedDate).isEqualTo("2016-12-07");
|
||||
assertThat(parsedDate).isEqualTo(someDate);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void daysInMonth() {
|
||||
int daysInMonth = YearMonth.of(1990, 2).lengthOfMonth();
|
||||
|
||||
assertThat(daysInMonth).isEqualTo(28);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package com.baeldung.datetime;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
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 {
|
||||
|
||||
private UseLocalDateTime useLocalDateTime = new UseLocalDateTime();
|
||||
|
||||
@Test
|
||||
public void givenString_whenUsingParse_thenLocalDateTime() {
|
||||
assertEquals(LocalDate.of(2016, Month.MAY, 10), useLocalDateTime.getLocalDateTimeUsingParseMethod("2016-05-10T06:30")
|
||||
.toLocalDate());
|
||||
assertEquals(LocalTime.of(6, 30), useLocalDateTime.getLocalDateTimeUsingParseMethod("2016-05-10T06:30")
|
||||
.toLocalTime());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLocalDateTime_whenSettingEndOfDay_thenReturnLastMomentOfDay() {
|
||||
LocalDateTime givenTimed = LocalDateTime.parse("2018-06-23T05:55:55");
|
||||
|
||||
LocalDateTime endOfDayFromGivenDirectly = useLocalDateTime.getEndOfDayFromLocalDateTimeDirectly(givenTimed);
|
||||
LocalDateTime endOfDayFromGiven = useLocalDateTime.getEndOfDayFromLocalDateTime(givenTimed);
|
||||
|
||||
assertThat(endOfDayFromGivenDirectly).isEqualTo(endOfDayFromGiven);
|
||||
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");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
package com.baeldung.datetime;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.time.DayOfWeek;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.LocalTime;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class UseLocalDateUnitTest {
|
||||
|
||||
private UseLocalDate useLocalDate = new UseLocalDate();
|
||||
|
||||
@Test
|
||||
public void givenValues_whenUsingFactoryOf_thenLocalDate() {
|
||||
assertEquals("2016-05-10", useLocalDate.getLocalDateUsingFactoryOfMethod(2016, 5, 10)
|
||||
.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_whenUsingParse_thenLocalDate() {
|
||||
assertEquals("2016-05-10", useLocalDate.getLocalDateUsingParseMethod("2016-05-10")
|
||||
.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingClock_thenLocalDate() {
|
||||
assertEquals(LocalDate.now(), useLocalDate.getLocalDateFromClock());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDate_whenUsingPlus_thenNextDay() {
|
||||
assertEquals(LocalDate.now()
|
||||
.plusDays(1), useLocalDate.getNextDay(LocalDate.now()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDate_whenUsingMinus_thenPreviousDay() {
|
||||
assertEquals(LocalDate.now()
|
||||
.minusDays(1), useLocalDate.getPreviousDay(LocalDate.now()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenToday_whenUsingGetDayOfWeek_thenDayOfWeek() {
|
||||
assertEquals(DayOfWeek.SUNDAY, useLocalDate.getDayOfWeek(LocalDate.parse("2016-05-22")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenToday_whenUsingWithTemporalAdjuster_thenFirstDayOfMonth() {
|
||||
assertEquals(1, useLocalDate.getFirstDayOfMonth()
|
||||
.getDayOfMonth());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLocalDate_whenUsingAtStartOfDay_thenReturnMidnight() {
|
||||
assertEquals(LocalDateTime.parse("2016-05-22T00:00:00"), useLocalDate.getStartOfDay(LocalDate.parse("2016-05-22")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLocalDate_whenSettingStartOfDay_thenReturnMidnightInAllCases() {
|
||||
LocalDate given = LocalDate.parse("2018-06-23");
|
||||
|
||||
LocalDateTime startOfDayWithMethod = useLocalDate.getStartOfDay(given);
|
||||
LocalDateTime startOfDayOfLocalDate = useLocalDate.getStartOfDayOfLocalDate(given);
|
||||
LocalDateTime startOfDayWithMin = useLocalDate.getStartOfDayAtMinTime(given);
|
||||
LocalDateTime startOfDayWithMidnight = useLocalDate.getStartOfDayAtMidnightTime(given);
|
||||
|
||||
assertThat(startOfDayWithMethod).isEqualTo(startOfDayWithMin)
|
||||
.isEqualTo(startOfDayWithMidnight)
|
||||
.isEqualTo(startOfDayOfLocalDate)
|
||||
.isEqualTo(LocalDateTime.parse("2018-06-23T00:00:00"));
|
||||
assertThat(startOfDayWithMin.toLocalTime()).isEqualTo(LocalTime.MIDNIGHT);
|
||||
assertThat(startOfDayWithMin.toString()).isEqualTo("2018-06-23T00:00");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLocalDate_whenSettingEndOfDay_thenReturnLastMomentOfDay() {
|
||||
LocalDate given = LocalDate.parse("2018-06-23");
|
||||
|
||||
LocalDateTime endOfDayWithMax = useLocalDate.getEndOfDay(given);
|
||||
LocalDateTime endOfDayFromLocalTime = useLocalDate.getEndOfDayFromLocalTime(given);
|
||||
|
||||
assertThat(endOfDayWithMax).isEqualTo(endOfDayFromLocalTime);
|
||||
assertThat(endOfDayWithMax.toLocalTime()).isEqualTo(LocalTime.MAX);
|
||||
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);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package com.baeldung.datetime;
|
||||
|
||||
import java.time.LocalTime;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class UseLocalTimeUnitTest {
|
||||
|
||||
private UseLocalTime useLocalTime = new UseLocalTime();
|
||||
|
||||
@Test
|
||||
public void givenValues_whenUsingFactoryOf_thenLocalTime() {
|
||||
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());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTime_whenAddHour_thenLocalTime() {
|
||||
Assert.assertEquals("07:30", useLocalTime.addAnHour(LocalTime.of(6, 30))
|
||||
.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getHourFromLocalTime() {
|
||||
Assert.assertEquals(1, useLocalTime.getHourFromLocalTime(LocalTime.of(1, 1)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getLocalTimeWithMinuteSetToValue() {
|
||||
Assert.assertEquals(LocalTime.of(10, 20), useLocalTime.getLocalTimeWithMinuteSetToValue(LocalTime.of(10, 10), 20));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.baeldung.datetime;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.Period;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class UsePeriodUnitTest {
|
||||
UsePeriod usingPeriod = new UsePeriod();
|
||||
|
||||
@Test
|
||||
public void givenPeriodAndLocalDate_thenCalculateModifiedDate() {
|
||||
Period period = Period.ofDays(1);
|
||||
LocalDate localDate = LocalDate.parse("2007-05-10");
|
||||
Assert.assertEquals(localDate.plusDays(1), usingPeriod.modifyDates(localDate, period));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDates_thenGetPeriod() {
|
||||
LocalDate localDate1 = LocalDate.parse("2007-05-10");
|
||||
LocalDate localDate2 = LocalDate.parse("2007-05-15");
|
||||
|
||||
Assert.assertEquals(Period.ofDays(5), usingPeriod.getDifferenceBetweenDates(localDate1, localDate2));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package com.baeldung.datetime;
|
||||
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneId;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
import java.util.TimeZone;
|
||||
|
||||
import org.joda.time.DateTime;
|
||||
import org.joda.time.DateTimeZone;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class UseTimeZoneUnitTest {
|
||||
|
||||
/* https://en.wikipedia.org/wiki/List_of_tz_database_time_zones */
|
||||
|
||||
String timeZone = "Asia/Singapore";
|
||||
|
||||
private static final String PATTERN = "E yyyy-MM-dd HH:mm:ss a";
|
||||
|
||||
@Test
|
||||
public void givenDateWithoutTimeZone_WhenSetTimeZoneUsingJava7_ThenTimeZoneIsSetSuccessfully() {
|
||||
Date nowUtc = new Date();
|
||||
TimeZone asiaSingapore = TimeZone.getTimeZone(timeZone);
|
||||
|
||||
Calendar nowAsiaSingapore = Calendar.getInstance(asiaSingapore);
|
||||
nowAsiaSingapore.setTime(nowUtc);
|
||||
|
||||
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(PATTERN);
|
||||
simpleDateFormat.setTimeZone(TimeZone.getTimeZone(timeZone));
|
||||
|
||||
System.out.println(String.format("Java7: Time now in '%s' is '%s'", nowAsiaSingapore.getTimeZone()
|
||||
.getID(), simpleDateFormat.format(nowAsiaSingapore.getTime())));
|
||||
|
||||
Assert.assertEquals(nowUtc.toInstant().getEpochSecond(), nowAsiaSingapore.toInstant().getEpochSecond());
|
||||
Assert.assertEquals(asiaSingapore, nowAsiaSingapore.getTimeZone());
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDateWithoutTimeZone_WhenSetTimeZoneUsingJava8_ThenTimeZoneIsSetSuccessfully() {
|
||||
Instant nowUtc = Instant.now();
|
||||
ZoneId asiaSingapore = ZoneId.of(timeZone);
|
||||
|
||||
ZonedDateTime nowAsiaSingapore = ZonedDateTime.ofInstant(nowUtc, asiaSingapore);
|
||||
|
||||
System.out.println(String.format("Java8: Time now in '%s' is '%s'", nowAsiaSingapore.getZone(),
|
||||
nowAsiaSingapore.format(DateTimeFormatter.ofPattern(PATTERN))));
|
||||
|
||||
Assert.assertEquals(nowUtc.getEpochSecond(), nowAsiaSingapore.toEpochSecond());
|
||||
Assert.assertEquals(asiaSingapore, nowAsiaSingapore.getZone());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDateWithoutTimeZone_WhenSetTimeZoneUsingJodaTime_ThenTimeZoneIsSetSuccessfully() {
|
||||
org.joda.time.Instant nowUtc = org.joda.time.Instant.now();
|
||||
DateTimeZone asiaSingapore = DateTimeZone.forID(timeZone);
|
||||
|
||||
DateTime nowAsiaSingapore = nowUtc.toDateTime(asiaSingapore);
|
||||
|
||||
System.out.println(String.format("Joda-time: Time now in '%s' is '%s'", nowAsiaSingapore.getZone(),
|
||||
nowAsiaSingapore.toString(PATTERN)));
|
||||
|
||||
Assert.assertEquals(nowUtc.toInstant().getMillis(), nowAsiaSingapore.toInstant().getMillis());
|
||||
Assert.assertEquals(asiaSingapore, nowAsiaSingapore.getZone());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package com.baeldung.datetime;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.time.LocalDate;
|
||||
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 {
|
||||
|
||||
private UseZonedDateTime zonedDateTime = new UseZonedDateTime();
|
||||
|
||||
@Test
|
||||
public void givenZoneId_thenZonedDateTime() {
|
||||
ZoneId zoneId = ZoneId.of("Europe/Paris");
|
||||
ZonedDateTime zonedDatetime = zonedDateTime.getZonedDateTime(LocalDateTime.parse("2016-05-20T06:30"), zoneId);
|
||||
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");
|
||||
ZoneId zone = ZoneId.of("Europe/Paris");
|
||||
ZonedDateTime zonedGiven = ZonedDateTime.of(given, LocalTime.NOON, zone);
|
||||
|
||||
ZonedDateTime startOfOfDayWithMethod = zonedDateTime.getStartOfDay(given, zone);
|
||||
ZonedDateTime startOfOfDayWithShorthandMethod = zonedDateTime.getStartOfDayShorthand(given, zone);
|
||||
ZonedDateTime startOfOfDayFromZonedDateTime = zonedDateTime.getStartOfDayFromZonedDateTime(zonedGiven);
|
||||
ZonedDateTime startOfOfDayAtMinTime = zonedDateTime.getStartOfDayAtMinTime(zonedGiven);
|
||||
ZonedDateTime startOfOfDayAtMidnightTime = zonedDateTime.getStartOfDayAtMidnightTime(zonedGiven);
|
||||
|
||||
assertThat(startOfOfDayWithMethod).isEqualTo(startOfOfDayWithShorthandMethod)
|
||||
.isEqualTo(startOfOfDayFromZonedDateTime)
|
||||
.isEqualTo(startOfOfDayAtMinTime)
|
||||
.isEqualTo(startOfOfDayAtMidnightTime);
|
||||
assertThat(startOfOfDayWithMethod.toLocalTime()).isEqualTo(LocalTime.MIDNIGHT);
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package com.baeldung.temporaladjusters;
|
||||
|
||||
import com.baeldung.temporaladjuster.CustomTemporalAdjuster;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.Period;
|
||||
import java.time.temporal.TemporalAdjuster;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class CustomTemporalAdjusterUnitTest {
|
||||
|
||||
private static final TemporalAdjuster NEXT_WORKING_DAY = new CustomTemporalAdjuster();
|
||||
|
||||
@Test
|
||||
public void whenAdjustAndImplementInterface_thenNextWorkingDay() {
|
||||
LocalDate localDate = LocalDate.of(2017, 07, 8);
|
||||
CustomTemporalAdjuster temporalAdjuster = new CustomTemporalAdjuster();
|
||||
LocalDate nextWorkingDay = localDate.with(temporalAdjuster);
|
||||
|
||||
assertEquals("2017-07-10", nextWorkingDay.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenAdjust_thenNextWorkingDay() {
|
||||
LocalDate localDate = LocalDate.of(2017, 07, 8);
|
||||
LocalDate date = localDate.with(NEXT_WORKING_DAY);
|
||||
|
||||
assertEquals("2017-07-10", date.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenAdjust_thenFourteenDaysAfterDate() {
|
||||
LocalDate localDate = LocalDate.of(2017, 07, 8);
|
||||
TemporalAdjuster temporalAdjuster = (t) -> t.plus(Period.ofDays(14));
|
||||
LocalDate result = localDate.with(temporalAdjuster);
|
||||
|
||||
String fourteenDaysAfterDate = "2017-07-22";
|
||||
|
||||
assertEquals(fourteenDaysAfterDate, result.toString());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.baeldung.temporaladjusters;
|
||||
|
||||
import java.time.DayOfWeek;
|
||||
import java.time.LocalDate;
|
||||
import java.time.temporal.TemporalAdjusters;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class TemporalAdjustersUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenAdjust_thenNextSunday() {
|
||||
LocalDate localDate = LocalDate.of(2017, 07, 8);
|
||||
LocalDate nextSunday = localDate.with(TemporalAdjusters.next(DayOfWeek.SUNDAY));
|
||||
|
||||
String expected = "2017-07-09";
|
||||
|
||||
Assert.assertEquals(expected, nextSunday.toString());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package com.baeldung.scanner;
|
||||
|
||||
import lombok.extern.log4j.Log4j;
|
||||
import org.apache.log4j.LogManager;
|
||||
import org.apache.log4j.PropertyConfigurator;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.Properties;
|
||||
import java.util.Scanner;
|
||||
|
||||
@Log4j
|
||||
public class HasNextVsHasNextLineDemo {
|
||||
private static final String LINE = "----------------------------";
|
||||
private static final String END_LINE = "--------OUTPUT--END---------\n";
|
||||
|
||||
|
||||
private static final String INPUT = new StringBuilder()
|
||||
.append("magic\tproject\n")
|
||||
.append(" database: oracle\n")
|
||||
.append("dependencies:\n")
|
||||
.append("spring:foo:bar\n")
|
||||
.append("\n").toString();
|
||||
|
||||
private static void hasNextBasic() {
|
||||
printHeader("hasNext() Basic");
|
||||
Scanner scanner = new Scanner(INPUT);
|
||||
while (scanner.hasNext()) {
|
||||
log.info(scanner.next());
|
||||
}
|
||||
log.info(END_LINE);
|
||||
scanner.close();
|
||||
}
|
||||
|
||||
private static void hasNextWithDelimiter() {
|
||||
printHeader("hasNext() with delimiter");
|
||||
Scanner scanner = new Scanner(INPUT);
|
||||
while (scanner.hasNext()) {
|
||||
String token = scanner.next();
|
||||
if ("dependencies:".equals(token)) {
|
||||
scanner.useDelimiter(":");
|
||||
}
|
||||
log.info(token);
|
||||
}
|
||||
log.info(END_LINE);
|
||||
scanner.close();
|
||||
}
|
||||
|
||||
private static void hasNextWithDelimiterFixed() {
|
||||
printHeader("hasNext() with delimiter FIX");
|
||||
Scanner scanner = new Scanner(INPUT);
|
||||
while (scanner.hasNext()) {
|
||||
String token = scanner.next();
|
||||
if ("dependencies:".equals(token)) {
|
||||
scanner.useDelimiter(":|\\s+");
|
||||
}
|
||||
log.info(token);
|
||||
}
|
||||
log.info(END_LINE);
|
||||
scanner.close();
|
||||
}
|
||||
|
||||
private static void addLineNumber() {
|
||||
printHeader("add line number by hasNextLine() ");
|
||||
Scanner scanner = new Scanner(INPUT);
|
||||
int i = 0;
|
||||
while (scanner.hasNextLine()) {
|
||||
log.info(String.format("%d|%s", ++i, scanner.nextLine()));
|
||||
}
|
||||
log.info(END_LINE);
|
||||
scanner.close();
|
||||
}
|
||||
|
||||
private static void printHeader(String title) {
|
||||
log.info(LINE);
|
||||
log.info(title);
|
||||
log.info(LINE);
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws IOException {
|
||||
setLogger();
|
||||
hasNextBasic();
|
||||
hasNextWithDelimiter();
|
||||
hasNextWithDelimiterFixed();
|
||||
addLineNumber();
|
||||
}
|
||||
|
||||
//overwrite the logger config
|
||||
private static void setLogger() throws IOException {
|
||||
InputStream is = HasNextVsHasNextLineDemo.class.getResourceAsStream("/scanner/log4j.properties");
|
||||
Properties props = new Properties();
|
||||
props.load(is);
|
||||
LogManager.resetConfiguration();
|
||||
PropertyConfigurator.configure(props);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
log4j.rootLogger=INFO, A1
|
||||
log4j.appender.A1=org.apache.log4j.ConsoleAppender
|
||||
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
|
||||
log4j.appender.A1.layout.ConversionPattern=[DEMO]%m%n
|
||||
@@ -50,6 +50,12 @@
|
||||
<artifactId>jmimemagic</artifactId>
|
||||
<version>${jmime-magic.version}</version>
|
||||
</dependency>
|
||||
<!-- Context Libraries -->
|
||||
<dependency>
|
||||
<groupId>com.sun.messaging.mq</groupId>
|
||||
<artifactId>fscontext</artifactId>
|
||||
<version>${fscontext.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
@@ -154,7 +160,7 @@
|
||||
<tika.version>1.18</tika.version>
|
||||
<jmime-magic.version>0.1.5</jmime-magic.version>
|
||||
<maven-jar-plugin.version>3.1.0</maven-jar-plugin.version>
|
||||
|
||||
<fscontext.version>4.4.2</fscontext.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
@@ -1,8 +1,12 @@
|
||||
=========
|
||||
|
||||
## Core Java JVM Cookbooks and Examples
|
||||
|
||||
This module contains articles about working with the Java Virtual Machine (JVM).
|
||||
|
||||
### Relevant Articles:
|
||||
|
||||
- [Method Inlining in the JVM](https://www.baeldung.com/jvm-method-inlining)
|
||||
- [JVM Log Forging](https://www.baeldung.com/jvm-log-forging)
|
||||
- [Guide to Java Instrumentation](https://www.baeldung.com/java-instrumentation)
|
||||
- [Class Loaders in Java](https://www.baeldung.com/java-classloaders)
|
||||
- [A Guide to System.exit()](https://www.baeldung.com/java-system-exit)
|
||||
- [Guide to System.gc()](https://www.baeldung.com/java-system-gc)
|
||||
|
||||
@@ -13,4 +13,49 @@
|
||||
<relativePath>../../</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>${junit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang3.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.javassist</groupId>
|
||||
<artifactId>javassist</artifactId>
|
||||
<version>${javaassist.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.owasp.esapi</groupId>
|
||||
<artifactId>esapi</artifactId>
|
||||
<version>${esapi.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.sun</groupId>
|
||||
<artifactId>tools</artifactId>
|
||||
<version>${sun.tools.version}</version>
|
||||
<scope>system</scope>
|
||||
<systemPath>${java.home}/../lib/tools.jar</systemPath>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<assertj.version>3.6.1</assertj.version>
|
||||
<!-- instrumentation -->
|
||||
<javaassist.version>3.21.0-GA</javaassist.version>
|
||||
<esapi.version>2.1.0.1</esapi.version>
|
||||
<sun.tools.version>1.8.0</sun.tools.version>
|
||||
</properties>
|
||||
</project>
|
||||
|
||||
@@ -3,9 +3,14 @@
|
||||
This module contains articles about working with the operating system (OS) in Java
|
||||
|
||||
### Relevant Articles:
|
||||
|
||||
- [Java 9 Process API Improvements](http://www.baeldung.com/java-9-process-api)
|
||||
- [Guide to java.lang.Process API](https://www.baeldung.com/java-process-api)
|
||||
- [Guide to java.lang.ProcessBuilder API](https://www.baeldung.com/java-lang-processbuilder-api)
|
||||
- [Get the Current Working Directory in Java](https://www.baeldung.com/java-current-directory)
|
||||
- [How to Detect the OS Using Java](http://www.baeldung.com/java-detect-os)
|
||||
- [How to Print Screen in Java](http://www.baeldung.com/print-screen-in-java)
|
||||
- [Pattern Search with Grep in Java](http://www.baeldung.com/grep-in-java)
|
||||
- [How to Run a Shell Command in Java](http://www.baeldung.com/run-shell-command-in-java)
|
||||
|
||||
This module uses Java 9, so make sure to have the JDK 9 installed to run it.
|
||||
@@ -42,6 +42,16 @@
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.unix4j</groupId>
|
||||
<artifactId>unix4j-command</artifactId>
|
||||
<version>${unix4j.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.googlecode.grep4j</groupId>
|
||||
<artifactId>grep4j</artifactId>
|
||||
<version>${grep4j.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
@@ -77,5 +87,7 @@
|
||||
<maven.compiler.source>1.9</maven.compiler.source>
|
||||
<maven.compiler.target>1.9</maven.compiler.target>
|
||||
<guava.version>25.1-jre</guava.version>
|
||||
<unix4j.version>0.4</unix4j.version>
|
||||
<grep4j.version>1.8.7</grep4j.version>
|
||||
</properties>
|
||||
</project>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package org.baeldung.java.shell;
|
||||
package com.baeldung.java.shell;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
16
core-java-modules/core-java-streams-2/README.md
Normal file
16
core-java-modules/core-java-streams-2/README.md
Normal file
@@ -0,0 +1,16 @@
|
||||
## Core Java streams
|
||||
|
||||
This module contains articles about the Stream API in Java.
|
||||
|
||||
### Relevant Articles:
|
||||
- [The Java 8 Stream API Tutorial](https://www.baeldung.com/java-8-streams)
|
||||
- [Introduction to Java 8 Streams](https://www.baeldung.com/java-8-streams-introduction)
|
||||
- [Java 8 Stream findFirst() vs. findAny()](https://www.baeldung.com/java-stream-findfirst-vs-findany)
|
||||
- [Guide to Stream.reduce()](https://www.baeldung.com/java-stream-reduce)
|
||||
- [Java IntStream Conversions](https://www.baeldung.com/java-intstream-convert)
|
||||
- [Java 8 Streams peek() API](https://www.baeldung.com/java-streams-peek-api)
|
||||
- [Working With Maps Using Streams](https://www.baeldung.com/java-maps-streams)
|
||||
- [Collect a Java Stream to an Immutable Collection](https://www.baeldung.com/java-stream-immutable-collection)
|
||||
- [How to Add a Single Element to a Stream](https://www.baeldung.com/java-stream-append-prepend)
|
||||
- [Operating on and Removing an Item from Stream](https://www.baeldung.com/java-use-remove-item-stream)
|
||||
- More articles: [[<-- prev>]](/../core-java-streams) [[next -->]](/../core-java-streams-3)
|
||||
53
core-java-modules/core-java-streams-2/pom.xml
Normal file
53
core-java-modules/core-java-streams-2/pom.xml
Normal file
@@ -0,0 +1,53 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>core-java-streams-2</artifactId>
|
||||
<version>1.0</version>
|
||||
<name>core-java-streams-2</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-java</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../../parent-java</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-core</artifactId>
|
||||
<version>${jmh-core.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-generator-annprocess</artifactId>
|
||||
<version>${jmh-generator.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>log4j</groupId>
|
||||
<artifactId>log4j</artifactId>
|
||||
<version>${log4j.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>${junit.version}</version>
|
||||
<scope>test</scope>
|
||||
<type>jar</type>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<maven.compiler.source>1.9</maven.compiler.source>
|
||||
<maven.compiler.target>1.9</maven.compiler.target>
|
||||
<assertj.version>3.11.1</assertj.version>
|
||||
</properties>
|
||||
</project>
|
||||
@@ -0,0 +1,39 @@
|
||||
package com.baeldung.reduce.application;
|
||||
|
||||
import com.baeldung.reduce.entities.User;
|
||||
import com.baeldung.reduce.utilities.NumberUtils;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
public class Application {
|
||||
|
||||
public static void main(String[] args) {
|
||||
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
|
||||
int result1 = numbers.stream().reduce(0, (subtotal, element) -> subtotal + element);
|
||||
System.out.println(result1);
|
||||
|
||||
int result2 = numbers.stream().reduce(0, Integer::sum);
|
||||
System.out.println(result2);
|
||||
|
||||
List<String> letters = Arrays.asList("a", "b", "c", "d", "e");
|
||||
String result3 = letters.stream().reduce("", (partialString, element) -> partialString + element);
|
||||
System.out.println(result3);
|
||||
|
||||
String result4 = letters.stream().reduce("", String::concat);
|
||||
System.out.println(result4);
|
||||
|
||||
String result5 = letters.stream().reduce("", (partialString, element) -> partialString.toUpperCase() + element.toUpperCase());
|
||||
System.out.println(result5);
|
||||
|
||||
List<User> users = Arrays.asList(new User("John", 30), new User("Julie", 35));
|
||||
int result6 = users.stream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum);
|
||||
System.out.println(result6);
|
||||
|
||||
String result7 = letters.parallelStream().reduce("", String::concat);
|
||||
System.out.println(result7);
|
||||
|
||||
int result8 = users.parallelStream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum);
|
||||
System.out.println(result8);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package com.baeldung.reduce.benchmarks;
|
||||
|
||||
import com.baeldung.reduce.entities.User;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import org.openjdk.jmh.annotations.Benchmark;
|
||||
import org.openjdk.jmh.annotations.BenchmarkMode;
|
||||
import org.openjdk.jmh.annotations.Mode;
|
||||
import org.openjdk.jmh.annotations.Scope;
|
||||
import org.openjdk.jmh.annotations.State;
|
||||
import org.openjdk.jmh.runner.Runner;
|
||||
import org.openjdk.jmh.runner.RunnerException;
|
||||
import org.openjdk.jmh.runner.options.Options;
|
||||
import org.openjdk.jmh.runner.options.OptionsBuilder;
|
||||
|
||||
@State(Scope.Thread)
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
public class JMHStreamReduceBenchMark {
|
||||
|
||||
private final List<User> userList = createUsers();
|
||||
|
||||
public static void main(String[] args) throws RunnerException {
|
||||
|
||||
Options options = new OptionsBuilder()
|
||||
.include(JMHStreamReduceBenchMark.class.getSimpleName()).threads(1)
|
||||
.forks(1).shouldFailOnError(true).shouldDoGC(true)
|
||||
.jvmArgs("-server").build();
|
||||
new Runner(options).run();
|
||||
}
|
||||
|
||||
private List<User> createUsers() {
|
||||
List<User> users = new ArrayList<>();
|
||||
for (int i = 0; i <= 1000000; i++) {
|
||||
users.add(new User("John" + i, i));
|
||||
}
|
||||
return users;
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public Integer executeReduceOnParallelizedStream() {
|
||||
return this.userList
|
||||
.parallelStream()
|
||||
.reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public Integer executeReduceOnSequentialStream() {
|
||||
return this.userList
|
||||
.stream()
|
||||
.reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.baeldung.reduce.entities;
|
||||
|
||||
public class User {
|
||||
|
||||
private final String name;
|
||||
private final int age;
|
||||
|
||||
public User(String name, int age) {
|
||||
this.name = name;
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public int getAge() {
|
||||
return age;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "User{" + "name=" + name + ", age=" + age + '}';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package com.baeldung.reduce.utilities;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.function.BiFunction;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
public abstract class NumberUtils {
|
||||
|
||||
private static final Logger LOGGER = Logger.getLogger(NumberUtils.class.getName());
|
||||
|
||||
public static int divideListElements(List<Integer> values, Integer divider) {
|
||||
return values.stream()
|
||||
.reduce(0, (a, b) -> {
|
||||
try {
|
||||
return a / divider + b / divider;
|
||||
} catch (ArithmeticException e) {
|
||||
LOGGER.log(Level.INFO, "Arithmetic Exception: Division by Zero");
|
||||
}
|
||||
return 0;
|
||||
});
|
||||
}
|
||||
|
||||
public static int divideListElementsWithExtractedTryCatchBlock(List<Integer> values, int divider) {
|
||||
return values.stream().reduce(0, (a, b) -> divide(a, divider) + divide(b, divider));
|
||||
}
|
||||
|
||||
public static int divideListElementsWithApplyFunctionMethod(List<Integer> values, int divider) {
|
||||
BiFunction<Integer, Integer, Integer> division = (a, b) -> a / b;
|
||||
return values.stream().reduce(0, (a, b) -> applyFunction(division, a, divider) + applyFunction(division, b, divider));
|
||||
}
|
||||
|
||||
private static int divide(int value, int factor) {
|
||||
int result = 0;
|
||||
try {
|
||||
result = value / factor;
|
||||
} catch (ArithmeticException e) {
|
||||
LOGGER.log(Level.INFO, "Arithmetic Exception: Division by Zero");
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private static int applyFunction(BiFunction<Integer, Integer, Integer> function, int a, int b) {
|
||||
try {
|
||||
return function.apply(a, b);
|
||||
}
|
||||
catch(Exception e) {
|
||||
LOGGER.log(Level.INFO, "Exception thrown!");
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.baeldung.streams;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.Collector;
|
||||
|
||||
public class MyImmutableListCollector {
|
||||
|
||||
public static <T, A extends List<T>> Collector<T, A, List<T>> toImmutableList(Supplier<A> supplier) {
|
||||
return Collector.of(supplier, List::add, (left, right) -> {
|
||||
left.addAll(right);
|
||||
return left;
|
||||
}, Collections::unmodifiableList);
|
||||
}
|
||||
|
||||
public static <T> Collector<T, List<T>, List<T>> toImmutableList() {
|
||||
return toImmutableList(ArrayList::new);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package com.baeldung.convert.intstreams;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class IntStreamsConversionsUnitTest {
|
||||
|
||||
@Test
|
||||
public void intStreamToArray() {
|
||||
int[] first50EvenNumbers = IntStream.iterate(0, i -> i + 2)
|
||||
.limit(50)
|
||||
.toArray();
|
||||
|
||||
assertThat(first50EvenNumbers).hasSize(50);
|
||||
assertThat(first50EvenNumbers[2]).isEqualTo(4);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void intStreamToList() {
|
||||
List<Integer> first50IntegerNumbers = IntStream.range(0, 50)
|
||||
.boxed()
|
||||
.collect(Collectors.toList());
|
||||
|
||||
assertThat(first50IntegerNumbers).hasSize(50);
|
||||
assertThat(first50IntegerNumbers.get(2)).isEqualTo(2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void intStreamToString() {
|
||||
String first3numbers = IntStream.of(0, 1, 2)
|
||||
.mapToObj(String::valueOf)
|
||||
.collect(Collectors.joining(", ", "[", "]"));
|
||||
|
||||
assertThat(first3numbers).isEqualTo("[0, 1, 2]");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package com.baeldung.reduce;
|
||||
|
||||
import com.baeldung.reduce.entities.User;
|
||||
import com.baeldung.reduce.utilities.NumberUtils;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class StreamReduceUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenIntegerList_whenReduceWithSumAccumulatorLambda_thenCorrect() {
|
||||
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
|
||||
int result = numbers.stream().reduce(0, (subtotal, element) -> subtotal + element);
|
||||
assertThat(result).isEqualTo(21);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenIntegerList_whenReduceWithSumAccumulatorMethodReference_thenCorrect() {
|
||||
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
|
||||
int result = numbers.stream().reduce(0, Integer::sum);
|
||||
assertThat(result).isEqualTo(21);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStringList_whenReduceWithConcatenatorAccumulatorLambda_thenCorrect() {
|
||||
List<String> letters = Arrays.asList("a", "b", "c", "d", "e");
|
||||
String result = letters.stream().reduce("", (partialString, element) -> partialString + element);
|
||||
assertThat(result).isEqualTo("abcde");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStringList_whenReduceWithConcatenatorAccumulatorMethodReference_thenCorrect() {
|
||||
List<String> letters = Arrays.asList("a", "b", "c", "d", "e");
|
||||
String result = letters.stream().reduce("", String::concat);
|
||||
assertThat(result).isEqualTo("abcde");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStringList_whenReduceWithUppercaseConcatenatorAccumulator_thenCorrect() {
|
||||
List<String> letters = Arrays.asList("a", "b", "c", "d", "e");
|
||||
String result = letters.stream().reduce("", (partialString, element) -> partialString.toUpperCase() + element.toUpperCase());
|
||||
assertThat(result).isEqualTo("ABCDE");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUserList_whenReduceWithAgeAccumulatorAndSumCombiner_thenCorrect() {
|
||||
List<User> users = Arrays.asList(new User("John", 30), new User("Julie", 35));
|
||||
int result = users.stream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum);
|
||||
assertThat(result).isEqualTo(65);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStringList_whenReduceWithParallelStream_thenCorrect() {
|
||||
List<String> letters = Arrays.asList("a", "b", "c", "d", "e");
|
||||
String result = letters.parallelStream().reduce("", String::concat);
|
||||
assertThat(result).isEqualTo("abcde");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNumberUtilsClass_whenCalledDivideListElements_thenCorrect() {
|
||||
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
|
||||
assertThat(NumberUtils.divideListElements(numbers, 1)).isEqualTo(21);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNumberUtilsClass_whenCalledDivideListElementsWithExtractedTryCatchBlock_thenCorrect() {
|
||||
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
|
||||
assertThat(NumberUtils.divideListElementsWithExtractedTryCatchBlock(numbers, 1)).isEqualTo(21);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStream_whneCalleddivideListElementsWithApplyFunctionMethod_thenCorrect() {
|
||||
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
|
||||
assertThat(NumberUtils.divideListElementsWithApplyFunctionMethod(numbers, 1)).isEqualTo(21);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.streams;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
public class Detail {
|
||||
|
||||
private static final List<String> PARTS = Arrays.asList("turbine", "pump");
|
||||
|
||||
public List<String> getParts() {
|
||||
return PARTS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.baeldung.streams;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.hamcrest.Matchers.anyOf;
|
||||
import static org.hamcrest.Matchers.is;
|
||||
import static org.junit.Assert.assertThat;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class Java8FindAnyFindFirstUnitTest {
|
||||
|
||||
@Test
|
||||
public void createStream_whenFindAnyResultIsPresent_thenCorrect() {
|
||||
|
||||
List<String> list = Arrays.asList("A", "B", "C", "D");
|
||||
|
||||
Optional<String> result = list.stream().findAny();
|
||||
|
||||
assertTrue(result.isPresent());
|
||||
assertThat(result.get(), anyOf(is("A"), is("B"), is("C"), is("D")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void createParallelStream_whenFindAnyResultIsPresent_thenCorrect() throws Exception {
|
||||
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
|
||||
Optional<Integer> result = list.stream().parallel().filter(num -> num < 4).findAny();
|
||||
|
||||
assertTrue(result.isPresent());
|
||||
assertThat(result.get(), anyOf(is(1), is(2), is(3)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void createStream_whenFindFirstResultIsPresent_thenCorrect() {
|
||||
|
||||
List<String> list = Arrays.asList("A", "B", "C", "D");
|
||||
|
||||
Optional<String> result = list.stream().findFirst();
|
||||
|
||||
assertTrue(result.isPresent());
|
||||
assertThat(result.get(), is("A"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
package com.baeldung.streams;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.BufferedWriter;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.Charset;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.*;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.*;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class Java8StreamApiUnitTest {
|
||||
|
||||
private long counter;
|
||||
|
||||
private static Logger log = LoggerFactory.getLogger(Java8StreamApiUnitTest.class);
|
||||
|
||||
private List<Product> productList;
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
productList = Arrays.asList(new Product(23, "potatoes"), new Product(14, "orange"), new Product(13, "lemon"), new Product(23, "bread"), new Product(13, "sugar"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void checkPipeline_whenStreamOneElementShorter_thenCorrect() {
|
||||
|
||||
List<String> list = Arrays.asList("abc1", "abc2", "abc3");
|
||||
long size = list.stream().skip(1).map(element -> element.substring(0, 3)).count();
|
||||
assertEquals(list.size() - 1, size);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void checkOrder_whenChangeQuantityOfMethodCalls_thenCorrect() {
|
||||
|
||||
List<String> list = Arrays.asList("abc1", "abc2", "abc3");
|
||||
|
||||
counter = 0;
|
||||
long sizeFirst = list.stream().skip(2).map(element -> {
|
||||
wasCalled();
|
||||
return element.substring(0, 3);
|
||||
}).count();
|
||||
assertEquals(1, counter);
|
||||
|
||||
counter = 0;
|
||||
long sizeSecond = list.stream().map(element -> {
|
||||
wasCalled();
|
||||
return element.substring(0, 3);
|
||||
}).skip(2).count();
|
||||
assertEquals(3, counter);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void createEmptyStream_whenEmpty_thenCorrect() {
|
||||
|
||||
Stream<String> streamEmpty = Stream.empty();
|
||||
assertEquals(0, streamEmpty.count());
|
||||
|
||||
List<String> names = Collections.emptyList();
|
||||
Stream<String> streamOf = Product.streamOf(names);
|
||||
assertTrue(streamOf.count() == 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void createStream_whenCreated_thenCorrect() {
|
||||
|
||||
Collection<String> collection = Arrays.asList("a", "b", "c");
|
||||
Stream<String> streamOfCollection = collection.stream();
|
||||
assertEquals(3, streamOfCollection.count());
|
||||
|
||||
Stream<String> streamOfArray = Stream.of("a", "b", "c");
|
||||
assertEquals(3, streamOfArray.count());
|
||||
|
||||
String[] arr = new String[] { "a", "b", "c" };
|
||||
Stream<String> streamOfArrayPart = Arrays.stream(arr, 1, 3);
|
||||
assertEquals(2, streamOfArrayPart.count());
|
||||
|
||||
IntStream intStream = IntStream.range(1, 3);
|
||||
LongStream longStream = LongStream.rangeClosed(1, 3);
|
||||
Random random = new Random();
|
||||
DoubleStream doubleStream = random.doubles(3);
|
||||
assertEquals(2, intStream.count());
|
||||
assertEquals(3, longStream.count());
|
||||
assertEquals(3, doubleStream.count());
|
||||
|
||||
IntStream streamOfChars = "abc".chars();
|
||||
IntStream str = "".chars();
|
||||
assertEquals(3, streamOfChars.count());
|
||||
|
||||
Stream<String> streamOfString = Pattern.compile(", ").splitAsStream("a, b, c");
|
||||
assertEquals("a", streamOfString.findFirst().get());
|
||||
|
||||
Path path = getPath();
|
||||
Stream<String> streamOfStrings = null;
|
||||
try {
|
||||
streamOfStrings = Files.lines(path, Charset.forName("UTF-8"));
|
||||
} catch (IOException e) {
|
||||
log.error("Error creating streams from paths {}", path, e.getMessage(), e);
|
||||
}
|
||||
assertEquals("a", streamOfStrings.findFirst().get());
|
||||
|
||||
Stream<String> streamBuilder = Stream.<String> builder().add("a").add("b").add("c").build();
|
||||
assertEquals(3, streamBuilder.count());
|
||||
|
||||
Stream<String> streamGenerated = Stream.generate(() -> "element").limit(10);
|
||||
assertEquals(10, streamGenerated.count());
|
||||
|
||||
Stream<Integer> streamIterated = Stream.iterate(40, n -> n + 2).limit(20);
|
||||
assertTrue(40 <= streamIterated.findAny().get());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void runStreamPipeline_whenOrderIsRight_thenCorrect() {
|
||||
|
||||
List<String> list = Arrays.asList("abc1", "abc2", "abc3");
|
||||
Optional<String> stream = list.stream().filter(element -> {
|
||||
log.info("filter() was called");
|
||||
return element.contains("2");
|
||||
}).map(element -> {
|
||||
log.info("map() was called");
|
||||
return element.toUpperCase();
|
||||
}).findFirst();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void reduce_whenExpected_thenCorrect() {
|
||||
|
||||
OptionalInt reduced = IntStream.range(1, 4).reduce((a, b) -> a + b);
|
||||
assertEquals(6, reduced.getAsInt());
|
||||
|
||||
int reducedTwoParams = IntStream.range(1, 4).reduce(10, (a, b) -> a + b);
|
||||
assertEquals(16, reducedTwoParams);
|
||||
|
||||
int reducedThreeParams = Stream.of(1, 2, 3).reduce(10, (a, b) -> a + b, (a, b) -> {
|
||||
log.info("combiner was called");
|
||||
return a + b;
|
||||
});
|
||||
assertEquals(16, reducedThreeParams);
|
||||
|
||||
int reducedThreeParamsParallel = Arrays.asList(1, 2, 3).parallelStream().reduce(10, (a, b) -> a + b, (a, b) -> {
|
||||
log.info("combiner was called");
|
||||
return a + b;
|
||||
});
|
||||
assertEquals(36, reducedThreeParamsParallel);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void collecting_whenAsExpected_thenCorrect() {
|
||||
|
||||
List<String> collectorCollection = productList.stream().map(Product::getName).collect(Collectors.toList());
|
||||
|
||||
assertTrue(collectorCollection instanceof List);
|
||||
assertEquals(5, collectorCollection.size());
|
||||
|
||||
String listToString = productList.stream().map(Product::getName).collect(Collectors.joining(", ", "[", "]"));
|
||||
|
||||
assertTrue(listToString.contains(",") && listToString.contains("[") && listToString.contains("]"));
|
||||
|
||||
double averagePrice = productList.stream().collect(Collectors.averagingInt(Product::getPrice));
|
||||
assertTrue(17.2 == averagePrice);
|
||||
|
||||
int summingPrice = productList.stream().collect(Collectors.summingInt(Product::getPrice));
|
||||
assertEquals(86, summingPrice);
|
||||
|
||||
IntSummaryStatistics statistics = productList.stream().collect(Collectors.summarizingInt(Product::getPrice));
|
||||
assertEquals(23, statistics.getMax());
|
||||
|
||||
Map<Integer, List<Product>> collectorMapOfLists = productList.stream().collect(Collectors.groupingBy(Product::getPrice));
|
||||
assertEquals(3, collectorMapOfLists.keySet().size());
|
||||
|
||||
Map<Boolean, List<Product>> mapPartioned = productList.stream().collect(Collectors.partitioningBy(element -> element.getPrice() > 15));
|
||||
assertEquals(2, mapPartioned.keySet().size());
|
||||
|
||||
}
|
||||
|
||||
@Test(expected = UnsupportedOperationException.class)
|
||||
public void collect_whenThrows_thenCorrect() {
|
||||
Set<Product> unmodifiableSet = productList.stream().collect(Collectors.collectingAndThen(Collectors.toSet(), Collections::unmodifiableSet));
|
||||
unmodifiableSet.add(new Product(4, "tea"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void customCollector_whenResultContainsAllElementsFrSource_thenCorrect() {
|
||||
Collector<Product, ?, LinkedList<Product>> toLinkedList = Collector.of(LinkedList::new, LinkedList::add, (first, second) -> {
|
||||
first.addAll(second);
|
||||
return first;
|
||||
});
|
||||
|
||||
LinkedList<Product> linkedListOfPersons = productList.stream().collect(toLinkedList);
|
||||
assertTrue(linkedListOfPersons.containsAll(productList));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void parallelStream_whenWorks_thenCorrect() {
|
||||
Stream<Product> streamOfCollection = productList.parallelStream();
|
||||
boolean isParallel = streamOfCollection.isParallel();
|
||||
boolean haveBigPrice = streamOfCollection.map(product -> product.getPrice() * 12).anyMatch(price -> price > 200);
|
||||
assertTrue(isParallel && haveBigPrice);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void parallel_whenIsParallel_thenCorrect() {
|
||||
IntStream intStreamParallel = IntStream.range(1, 150).parallel().map(element -> element * 34);
|
||||
boolean isParallel = intStreamParallel.isParallel();
|
||||
assertTrue(isParallel);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void parallel_whenIsSequential_thenCorrect() {
|
||||
IntStream intStreamParallel = IntStream.range(1, 150).parallel().map(element -> element * 34);
|
||||
IntStream intStreamSequential = intStreamParallel.sequential();
|
||||
boolean isParallel = intStreamParallel.isParallel();
|
||||
assertFalse(isParallel);
|
||||
}
|
||||
|
||||
private Path getPath() {
|
||||
Path path = null;
|
||||
try {
|
||||
path = Files.createTempFile(null, ".txt");
|
||||
} catch (IOException e) {
|
||||
log.error(e.getMessage());
|
||||
}
|
||||
|
||||
try (BufferedWriter writer = Files.newBufferedWriter(path)) {
|
||||
writer.write("a\nb\nc");
|
||||
} catch (IOException e) {
|
||||
log.error(e.getMessage());
|
||||
}
|
||||
return path;
|
||||
}
|
||||
|
||||
private void wasCalled() {
|
||||
counter++;
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user