BAEL-20573: Rename core-java-datetime-computations to core-java-date-operations-1
This commit is contained in:
15
core-java-modules/core-java-date-operations-1/README.md
Normal file
15
core-java-modules/core-java-date-operations-1/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)
|
||||
73
core-java-modules/core-java-date-operations-1/pom.xml
Normal file
73
core-java-modules/core-java-date-operations-1/pom.xml
Normal file
@@ -0,0 +1,73 @@
|
||||
<?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-date-operations-1</artifactId>
|
||||
<version>${project.parent.version}</version>
|
||||
<name>core-java-date-operations-1</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-date-operations-1</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());
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user