[BAEL-8456] - Moved Java Date articles into a new module - 'java-dates'

This commit is contained in:
amit2103
2018-08-25 17:44:06 +05:30
parent f60debdcd3
commit 3bd1ed4ece
67 changed files with 177 additions and 28 deletions

View File

@@ -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();
}
}

View File

@@ -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);
}
}

View File

@@ -0,0 +1,2 @@
### Relevant Articles:
- [Introduction to the Java 8 Date/Time API](http://www.baeldung.com/java-8-date-time-intro)

View File

@@ -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);
}
}

View File

@@ -0,0 +1,73 @@
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;
}
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;
}
}

View File

@@ -0,0 +1,24 @@
package com.baeldung.datetime;
import java.time.LocalDateTime;
import java.time.LocalTime;
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;
}
}

View File

@@ -0,0 +1,31 @@
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 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);
}
}

View File

@@ -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);
}
}

View File

@@ -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());
}
}

View File

@@ -0,0 +1,42 @@
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 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;
}
}

View File

@@ -0,0 +1,39 @@
/**
*
*/
package com.baeldung.java9.datetime;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;
/**
* Class which shows a way to convert java.util.Date into java.time.LocalDate.
*
* @author abialas
*
*/
public class DateToLocalDateConverter {
public static LocalDate convertToLocalDateViaInstant(Date dateToConvert) {
return dateToConvert.toInstant()
.atZone(ZoneId.systemDefault())
.toLocalDate();
}
public static LocalDate convertToLocalDateViaSqlDate(Date dateToConvert) {
return new java.sql.Date(dateToConvert.getTime()).toLocalDate();
}
public static LocalDate convertToLocalDateViaMilisecond(Date dateToConvert) {
return Instant.ofEpochMilli(dateToConvert.getTime())
.atZone(ZoneId.systemDefault())
.toLocalDate();
}
public static LocalDate convertToLocalDate(Date dateToConvert) {
return LocalDate.ofInstant(dateToConvert.toInstant(), ZoneId.systemDefault());
}
}

View File

@@ -0,0 +1,39 @@
/**
*
*/
package com.baeldung.java9.datetime;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
/**
* Class which shows a way to convert java.util.Date into java.time.LocalDateTime.
*
* @author abialas
*
*/
public class DateToLocalDateTimeConverter {
public static LocalDateTime convertToLocalDateTimeViaInstant(Date dateToConvert) {
return dateToConvert.toInstant()
.atZone(ZoneId.systemDefault())
.toLocalDateTime();
}
public static LocalDateTime convertToLocalDateTimeViaSqlTimestamp(Date dateToConvert) {
return new java.sql.Timestamp(dateToConvert.getTime()).toLocalDateTime();
}
public static LocalDateTime convertToLocalDateTimeViaMilisecond(Date dateToConvert) {
return Instant.ofEpochMilli(dateToConvert.getTime())
.atZone(ZoneId.systemDefault())
.toLocalDateTime();
}
public static LocalDateTime convertToLocalDateTime(Date dateToConvert) {
return LocalDateTime.ofInstant(dateToConvert.toInstant(), ZoneId.systemDefault());
}
}

View File

@@ -0,0 +1,27 @@
/**
*
*/
package com.baeldung.java9.datetime;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
/**
* Class which shows different ways of converting java.time.LocalDateTime into java.util.Date.
*
* @author abialas
*
*/
public class LocalDateTimeToDateConverter {
public static Date convertToDateViaSqlTimestamp(LocalDateTime dateToConvert) {
return java.sql.Timestamp.valueOf(dateToConvert);
}
public static Date convertToDateViaInstant(LocalDateTime dateToConvert) {
return java.util.Date.from(dateToConvert.atZone(ZoneId.systemDefault())
.toInstant());
}
}

View File

@@ -0,0 +1,28 @@
/**
*
*/
package com.baeldung.java9.datetime;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;
/**
* Class which shows different ways of converting java.time.LocalDate into java.util.Date.
*
* @author abialas
*
*/
public class LocalDateToDateConverter {
public static Date convertToDateViaSqlDate(LocalDate dateToConvert) {
return java.sql.Date.valueOf(dateToConvert);
}
public static Date convertToDateViaInstant(LocalDate dateToConvert) {
return java.util.Date.from(dateToConvert.atStartOfDay()
.atZone(ZoneId.systemDefault())
.toInstant());
}
}

View File

@@ -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());
}
}

View File

@@ -0,0 +1,7 @@
package com.baeldung.regexp.datepattern;
public interface DateMatcher {
boolean matches(String date);
}

View File

@@ -0,0 +1,14 @@
package com.baeldung.regexp.datepattern;
import java.util.regex.Pattern;
class FormattedDateMatcher implements DateMatcher {
private static final Pattern DATE_PATTERN = Pattern.compile(
"^\\d{4}-\\d{2}-\\d{2}$");
@Override
public boolean matches(String date) {
return DATE_PATTERN.matcher(date).matches();
}
}

View File

@@ -0,0 +1,14 @@
package com.baeldung.regexp.datepattern;
import java.util.regex.Pattern;
class RangedDateMatcher implements DateMatcher {
private static final Pattern DATE_PATTERN = Pattern.compile(
"^((19|2[0-9])[0-9]{2})-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])$");
@Override
public boolean matches(String date) {
return DATE_PATTERN.matcher(date).matches();
}
}

View File

@@ -0,0 +1,16 @@
package com.baeldung.regexp.datepattern.gregorian;
import com.baeldung.regexp.datepattern.DateMatcher;
import java.util.regex.Pattern;
public class February29thMatcher implements DateMatcher {
private static final Pattern DATE_PATTERN = Pattern.compile(
"^((2000|2400|2800|(19|2[0-9](0[48]|[2468][048]|[13579][26])))-02-29)$");
@Override
public boolean matches(String date) {
return DATE_PATTERN.matcher(date).matches();
}
}

View File

@@ -0,0 +1,16 @@
package com.baeldung.regexp.datepattern.gregorian;
import com.baeldung.regexp.datepattern.DateMatcher;
import java.util.regex.Pattern;
public class FebruaryGeneralMatcher implements DateMatcher {
private static final Pattern DATE_PATTERN = Pattern.compile(
"^(((19|2[0-9])[0-9]{2})-02-(0[1-9]|1[0-9]|2[0-8]))$");
@Override
public boolean matches(String date) {
return DATE_PATTERN.matcher(date).matches();
}
}

View File

@@ -0,0 +1,19 @@
package com.baeldung.regexp.datepattern.gregorian;
import com.baeldung.regexp.datepattern.DateMatcher;
import java.util.regex.Pattern;
class GregorianDateMatcher implements DateMatcher {
private static final Pattern DATE_PATTERN = Pattern.compile(
"^((2000|2400|2800|(19|2[0-9](0[48]|[2468][048]|[13579][26])))-02-29)$"
+ "|^(((19|2[0-9])[0-9]{2})-02-(0[1-9]|1[0-9]|2[0-8]))$"
+ "|^(((19|2[0-9])[0-9]{2})-(0[13578]|10|12)-(0[1-9]|[12][0-9]|3[01]))$"
+ "|^(((19|2[0-9])[0-9]{2})-(0[469]|11)-(0[1-9]|[12][0-9]|30))$");
@Override
public boolean matches(String date) {
return DATE_PATTERN.matcher(date).matches();
}
}

View File

@@ -0,0 +1,17 @@
package com.baeldung.regexp.datepattern.gregorian;
import com.baeldung.regexp.datepattern.DateMatcher;
import java.util.regex.Pattern;
public class MonthsOf30DaysMatcher implements DateMatcher {
private static final Pattern DATE_PATTERN = Pattern.compile(
"^(((19|2[0-9])[0-9]{2})-(0[469]|11)-(0[1-9]|[12][0-9]|30))$");
@Override
public boolean matches(String date) {
return DATE_PATTERN.matcher(date).matches();
}
}

View File

@@ -0,0 +1,17 @@
package com.baeldung.regexp.datepattern.gregorian;
import com.baeldung.regexp.datepattern.DateMatcher;
import java.util.regex.Pattern;
public class MonthsOf31DaysMatcher implements DateMatcher {
private static final Pattern DATE_PATTERN = Pattern.compile(
"^(((19|2[0-9])[0-9]{2})-(0[13578]|10|12)-(0[1-9]|[12][0-9]|3[01]))$");
@Override
public boolean matches(String date) {
return DATE_PATTERN.matcher(date).matches();
}
}

View File

@@ -0,0 +1,6 @@
package com.baeldung.regexp.datepattern.optmization;
public class OptimizedMatcher {
}

View File

@@ -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);
}
}
}

View File

@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@@ -0,0 +1,70 @@
package com.baeldung.date;
import org.junit.Test;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.assertEquals;
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 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 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);
}
}

View File

@@ -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));
}
}

View File

@@ -0,0 +1,141 @@
package com.baeldung.date;
import static org.junit.Assert.assertEquals;
import static org.assertj.core.api.Assertions.assertThat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
import org.apache.commons.lang3.time.DateUtils;
import org.joda.time.DateTime;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
public class StringToDateUnitTest {
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void givenDateString_whenConvertedToDate_thenWeGetCorrectLocalDate() {
LocalDate expectedLocalDate = LocalDate.of(2018, 05, 05);
LocalDate date = LocalDate.parse("2018-05-05");
assertThat(date).isEqualTo(expectedLocalDate);
}
@Test
public void givenDateString_whenConvertedToDate_thenWeGetCorrectLocalDateTime() {
LocalDateTime expectedLocalDateTime = LocalDateTime.of(2018, 05, 05, 11, 50, 55);
LocalDateTime dateTime = LocalDateTime.parse("2018-05-05T11:50:55");
assertThat(dateTime).isEqualTo(expectedLocalDateTime);
}
@Test
public void givenDateString_whenConvertedToDate_thenWeGetDateTimeParseException() {
thrown.expect(DateTimeParseException.class);
thrown.expectMessage("Text '2018-05-05' could not be parsed at index 10");
LocalDateTime.parse("2018-05-05");
}
@Test
public void givenDateString_whenConvertedToDate_thenWeGetCorrectZonedDateTime() {
LocalDateTime localDateTime = LocalDateTime.of(2015, 05, 05, 10, 15, 30);
ZonedDateTime expectedZonedDateTime = ZonedDateTime.of(localDateTime, ZoneId.of("Europe/Paris"));
ZonedDateTime zonedDateTime = ZonedDateTime.parse("2015-05-05T10:15:30+01:00[Europe/Paris]");
assertThat(zonedDateTime).isEqualTo(expectedZonedDateTime);
}
@Test
public void givenDateString_whenConvertedToDateUsingFormatter_thenWeGetCorrectLocalDate() {
LocalDate expectedLocalDate = LocalDate.of(1959, 7, 9);
String dateInString = "19590709";
LocalDate date = LocalDate.parse(dateInString, DateTimeFormatter.BASIC_ISO_DATE);
assertThat(date).isEqualTo(expectedLocalDate);
}
@Test
public void givenDateString_whenConvertedToDateUsingCustomFormatter_thenWeGetCorrectLocalDate() {
LocalDate expectedLocalDate = LocalDate.of(1980, 05, 05);
String dateInString = "Mon, 05 May 1980";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE, d MMM yyyy", Locale.ENGLISH);
LocalDate dateTime = LocalDate.parse(dateInString, formatter);
assertThat(dateTime).isEqualTo(expectedLocalDate);
}
@Test
public void givenDateString_whenConvertedToDate_thenWeGetCorrectDate() throws ParseException {
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy", Locale.ENGLISH);
String dateInString = "7-Jun-2013";
Date date = formatter.parse(dateInString);
assertDateIsCorrect(date);
}
@Test
public void givenDateString_whenConvertedToDate_thenWeGetParseException() throws ParseException {
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy", Locale.ENGLISH);
thrown.expect(ParseException.class);
thrown.expectMessage("Unparseable date: \"07/06/2013\"");
String dateInString = "07/06/2013";
formatter.parse(dateInString);
}
@Test
public void givenDateString_whenConvertedToDate_thenWeGetCorrectJodaDateTime() {
org.joda.time.format.DateTimeFormatter formatter = org.joda.time.format.DateTimeFormat.forPattern("dd/MM/yyyy HH:mm:ss");
String dateInString = "07/06/2013 10:11:59";
DateTime dateTime = DateTime.parse(dateInString, formatter);
assertEquals("Day of Month should be 7: ", 7, dateTime.getDayOfMonth());
assertEquals("Month should be: ", 6, dateTime.getMonthOfYear());
assertEquals("Year should be: ", 2013, dateTime.getYear());
assertEquals("Hour of day should be: ", 10, dateTime.getHourOfDay());
assertEquals("Minutes of hour should be: ", 11, dateTime.getMinuteOfHour());
assertEquals("Seconds of minute should be: ", 59, dateTime.getSecondOfMinute());
}
@Test
public void givenDateString_whenConvertedToDate_thenWeGetCorrectDateTime() throws ParseException {
String dateInString = "07/06-2013";
Date date = DateUtils.parseDate(dateInString, new String[] { "yyyy-MM-dd HH:mm:ss", "dd/MM-yyyy" });
assertDateIsCorrect(date);
}
private void assertDateIsCorrect(Date date) {
Calendar calendar = new GregorianCalendar(Locale.ENGLISH);
calendar.setTime(date);
assertEquals("Day of Month should be 7: ", 7, calendar.get(Calendar.DAY_OF_MONTH));
assertEquals("Month should be: ", 5, calendar.get(Calendar.MONTH));
assertEquals("Year should be: ", 2013, calendar.get(Calendar.YEAR));
}
}

View File

@@ -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();
}
}

View File

@@ -0,0 +1,42 @@
package com.baeldung.dateapi;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import org.junit.Test;
public class JavaDurationUnitTest {
@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");
}
}

View File

@@ -0,0 +1,44 @@
package com.baeldung.dateapi;
import org.apache.log4j.Logger;
import org.junit.Test;
import java.time.LocalDate;
import java.time.Period;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
public class JavaPeriodUnitTest {
private static final Logger LOG = Logger.getLogger(JavaPeriodUnitTest.class);
@Test
public void 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());
}
}

View File

@@ -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);
}
}

View File

@@ -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);
}
}

View File

@@ -0,0 +1,36 @@
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 org.junit.Test;
public class UseLocalDateTimeUnitTest {
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");
}
}

View File

@@ -0,0 +1,91 @@
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 {
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");
}
}

View File

@@ -0,0 +1,36 @@
package com.baeldung.datetime;
import java.time.LocalTime;
import org.junit.Assert;
import org.junit.Test;
public class UseLocalTimeUnitTest {
UseLocalTime useLocalTime = new UseLocalTime();
@Test
public void givenValues_whenUsingFactoryOf_thenLocalTime() {
Assert.assertEquals("07:07:07", useLocalTime.getLocalTimeUsingFactoryOfMethod(7, 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));
}
}

View File

@@ -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));
}
}

View File

@@ -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());
}
}

View File

@@ -0,0 +1,45 @@
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 org.junit.Assert;
import org.junit.Test;
public class UseZonedDateTimeUnitTest {
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 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");
}
}

View File

@@ -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);
}
}
}

View File

@@ -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);
}
}

View File

@@ -0,0 +1,89 @@
/**
*
*/
package com.baeldung.java9.datetime;
import static org.junit.Assert.assertEquals;
import java.time.LocalDate;
import java.time.temporal.ChronoField;
import java.util.Calendar;
import java.util.Date;
import org.junit.Test;
import com.baeldung.java9.datetime.DateToLocalDateConverter;
/**
* JUnits for {@link DateToLocalDateConverter} class.
*
* @author abialas
*
*/
public class DateToLocalDateConverterUnitTest {
@Test
public void shouldReturn10thNovember2010WhenConvertViaInstant() {
// given
Calendar calendar = Calendar.getInstance();
calendar.set(2010, 10, 10);
Date dateToConvert = calendar.getTime();
// when
LocalDate localDate = DateToLocalDateConverter.convertToLocalDateViaInstant(dateToConvert);
// then
assertEquals(2010, localDate.get(ChronoField.YEAR));
assertEquals(11, localDate.get(ChronoField.MONTH_OF_YEAR));
assertEquals(10, localDate.get(ChronoField.DAY_OF_MONTH));
}
@Test
public void shouldReturn10thNovember2010WhenConvertViaMiliseconds() {
// given
Calendar calendar = Calendar.getInstance();
calendar.set(2010, 10, 10);
Date dateToConvert = calendar.getTime();
// when
LocalDate localDate = DateToLocalDateConverter.convertToLocalDateViaMilisecond(dateToConvert);
// then
assertEquals(2010, localDate.get(ChronoField.YEAR));
assertEquals(11, localDate.get(ChronoField.MONTH_OF_YEAR));
assertEquals(10, localDate.get(ChronoField.DAY_OF_MONTH));
}
@Test
public void shouldReturn10thNovember2010WhenConvertViaSqlDate() {
// given
Calendar calendar = Calendar.getInstance();
calendar.set(2010, 10, 10);
Date dateToConvert = calendar.getTime();
// when
LocalDate localDate = DateToLocalDateConverter.convertToLocalDateViaSqlDate(dateToConvert);
// then
assertEquals(2010, localDate.get(ChronoField.YEAR));
assertEquals(11, localDate.get(ChronoField.MONTH_OF_YEAR));
assertEquals(10, localDate.get(ChronoField.DAY_OF_MONTH));
}
@Test
public void shouldReturn10thNovember2010WhenConvertToLocalDate() {
// given
Calendar calendar = Calendar.getInstance();
calendar.set(2010, 10, 10);
Date dateToConvert = calendar.getTime();
// when
LocalDate localDateTime = DateToLocalDateConverter.convertToLocalDate(dateToConvert);
// then
assertEquals(2010, localDateTime.get(ChronoField.YEAR));
assertEquals(11, localDateTime.get(ChronoField.MONTH_OF_YEAR));
assertEquals(10, localDateTime.get(ChronoField.DAY_OF_MONTH));
}
}

View File

@@ -0,0 +1,97 @@
/**
*
*/
package com.baeldung.java9.datetime;
import static org.junit.Assert.assertEquals;
import java.time.LocalDateTime;
import java.time.temporal.ChronoField;
import java.util.Calendar;
import java.util.Date;
import org.junit.Test;
import com.baeldung.java9.datetime.DateToLocalDateTimeConverter;
/**
* JUnits for {@link DateToLocalDateTimeConverter} class.
*
* @author abialas
*
*/
public class DateToLocalDateTimeConverterUnitTest {
@Test
public void shouldReturn10thNovember2010time8hour20minWhenConvertViaInstant() {
// given
Calendar calendar = Calendar.getInstance();
calendar.set(2010, 10, 10, 8, 20);
Date dateToConvert = calendar.getTime();
// when
LocalDateTime localDateTime = DateToLocalDateTimeConverter.convertToLocalDateTimeViaInstant(dateToConvert);
// then
assertEquals(2010, localDateTime.get(ChronoField.YEAR));
assertEquals(11, localDateTime.get(ChronoField.MONTH_OF_YEAR));
assertEquals(10, localDateTime.get(ChronoField.DAY_OF_MONTH));
assertEquals(8, localDateTime.get(ChronoField.HOUR_OF_DAY));
assertEquals(20, localDateTime.get(ChronoField.MINUTE_OF_HOUR));
}
@Test
public void shouldReturn10thNovember2010time8hour20minWhenConvertViaMiliseconds() {
// given
Calendar calendar = Calendar.getInstance();
calendar.set(2010, 10, 10, 8, 20);
Date dateToConvert = calendar.getTime();
// when
LocalDateTime localDateTime = DateToLocalDateTimeConverter.convertToLocalDateTimeViaMilisecond(dateToConvert);
// then
assertEquals(2010, localDateTime.get(ChronoField.YEAR));
assertEquals(11, localDateTime.get(ChronoField.MONTH_OF_YEAR));
assertEquals(10, localDateTime.get(ChronoField.DAY_OF_MONTH));
assertEquals(8, localDateTime.get(ChronoField.HOUR_OF_DAY));
assertEquals(20, localDateTime.get(ChronoField.MINUTE_OF_HOUR));
}
@Test
public void shouldReturn10thNovember2010time8hour20minWhenConvertViaSqlTimestamp() {
// given
Calendar calendar = Calendar.getInstance();
calendar.set(2010, 10, 10, 8, 20);
Date dateToConvert = calendar.getTime();
// when
LocalDateTime localDateTime = DateToLocalDateTimeConverter.convertToLocalDateTimeViaSqlTimestamp(dateToConvert);
// then
assertEquals(2010, localDateTime.get(ChronoField.YEAR));
assertEquals(11, localDateTime.get(ChronoField.MONTH_OF_YEAR));
assertEquals(10, localDateTime.get(ChronoField.DAY_OF_MONTH));
assertEquals(8, localDateTime.get(ChronoField.HOUR_OF_DAY));
assertEquals(20, localDateTime.get(ChronoField.MINUTE_OF_HOUR));
}
@Test
public void shouldReturn10thNovember2010time8hour20minWhenConvertToLocalDateTime() {
// given
Calendar calendar = Calendar.getInstance();
calendar.set(2010, 10, 10, 8, 20);
Date dateToConvert = calendar.getTime();
// when
LocalDateTime localDateTime = DateToLocalDateTimeConverter.convertToLocalDateTime(dateToConvert);
// then
assertEquals(2010, localDateTime.get(ChronoField.YEAR));
assertEquals(11, localDateTime.get(ChronoField.MONTH_OF_YEAR));
assertEquals(10, localDateTime.get(ChronoField.DAY_OF_MONTH));
assertEquals(8, localDateTime.get(ChronoField.HOUR_OF_DAY));
assertEquals(20, localDateTime.get(ChronoField.MINUTE_OF_HOUR));
}
}

View File

@@ -0,0 +1,61 @@
/**
*
*/
package com.baeldung.java9.datetime;
import static org.junit.Assert.assertEquals;
import java.time.LocalDateTime;
import java.util.Calendar;
import java.util.Date;
import org.junit.Test;
/**
*
* JUnits for {@link LocalDateTimeToDateConverter} class.
*
* @author abialas
*
*/
public class LocalDateTimeToDateConverterUnitTest {
@Test
public void shouldReturn10thNovember2010time8hour20minWhenConvertViaInstant() {
// given
LocalDateTime dateToConvert = LocalDateTime.of(2010, 11, 10, 8, 20);
// when
Date date = LocalDateTimeToDateConverter.convertToDateViaInstant(dateToConvert);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
// then
assertEquals(2010, calendar.get(Calendar.YEAR));
assertEquals(10, calendar.get(Calendar.MONTH));
assertEquals(10, calendar.get(Calendar.DAY_OF_MONTH));
assertEquals(8, calendar.get(Calendar.HOUR));
assertEquals(20, calendar.get(Calendar.MINUTE));
assertEquals(0, calendar.get(Calendar.SECOND));
}
@Test
public void shouldReturn10thNovember2010WhenConvertViaSqlTimestamp() {
// given
LocalDateTime dateToConvert = LocalDateTime.of(2010, 11, 10, 8, 20);
// when
Date date = LocalDateTimeToDateConverter.convertToDateViaSqlTimestamp(dateToConvert);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
// then
assertEquals(2010, calendar.get(Calendar.YEAR));
assertEquals(10, calendar.get(Calendar.MONTH));
assertEquals(10, calendar.get(Calendar.DAY_OF_MONTH));
assertEquals(8, calendar.get(Calendar.HOUR));
assertEquals(20, calendar.get(Calendar.MINUTE));
assertEquals(0, calendar.get(Calendar.SECOND));
}
}

View File

@@ -0,0 +1,55 @@
/**
*
*/
package com.baeldung.java9.datetime;
import static org.junit.Assert.assertEquals;
import java.time.LocalDate;
import java.util.Calendar;
import java.util.Date;
import org.junit.Test;
/**
*
* JUnits for {@link LocalDateToDateConverter} class.
*
* @author abialas
*
*/
public class LocalDateToDateConverterUnitTest {
@Test
public void shouldReturn10thNovember2010WhenConvertViaInstant() {
// given
LocalDate dateToConvert = LocalDate.of(2010, 11, 10);
// when
Date date = LocalDateToDateConverter.convertToDateViaInstant(dateToConvert);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
// then
assertEquals(2010, calendar.get(Calendar.YEAR));
assertEquals(10, calendar.get(Calendar.MONTH));
assertEquals(10, calendar.get(Calendar.DAY_OF_MONTH));
}
@Test
public void shouldReturn10thNovember2010WhenConvertViaSqlDate() {
// given
LocalDate dateToConvert = LocalDate.of(2010, 11, 10);
// when
Date date = LocalDateToDateConverter.convertToDateViaSqlDate(dateToConvert);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
// then
assertEquals(2010, calendar.get(Calendar.YEAR));
assertEquals(10, calendar.get(Calendar.MONTH));
assertEquals(10, calendar.get(Calendar.DAY_OF_MONTH));
}
}

View File

@@ -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(), 3);
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));
}
}

View File

@@ -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());
}
}

View File

@@ -0,0 +1,24 @@
package com.baeldung.regexp.datepattern;
import org.junit.Assert;
import org.junit.Test;
public class FormattedDateMatcherUnitTest {
private DateMatcher matcher = new FormattedDateMatcher();
@Test
public void whenUsingFormattedDateMatcher_thenFormatConstraintsSatisfied() {
Assert.assertTrue(matcher.matches("2017-12-31"));
Assert.assertTrue(matcher.matches("2018-01-01"));
Assert.assertTrue(matcher.matches("0000-00-00"));
Assert.assertTrue(matcher.matches("1029-99-72"));
Assert.assertFalse(matcher.matches("2018-01"));
Assert.assertFalse(matcher.matches("2018-01-01-01"));
Assert.assertFalse(matcher.matches("2018-01-XX"));
Assert.assertFalse(matcher.matches(" 2018-01-01"));
Assert.assertFalse(matcher.matches("2018-01-01 "));
Assert.assertFalse(matcher.matches("2018/01/01"));
}
}

View File

@@ -0,0 +1,31 @@
package com.baeldung.regexp.datepattern;
import org.junit.Assert;
import org.junit.Test;
public class RangedDateMatcherUnitTest {
private DateMatcher matcher = new RangedDateMatcher();
@Test
public void whenUsingRangedDateMatcher_thenFormatConstraintsSatisfied() {
Assert.assertFalse(matcher.matches("2018-01"));
Assert.assertFalse(matcher.matches("2018-01-01-01"));
Assert.assertFalse(matcher.matches("2018-01-XX"));
Assert.assertFalse(matcher.matches(" 2018-01-01"));
Assert.assertFalse(matcher.matches("2018-01-01 "));
Assert.assertFalse(matcher.matches("2018/01/01"));
}
@Test
public void whenUsingRangedDateMatcher_thenRangeConstraintsSatisfied() {
Assert.assertTrue(matcher.matches("1900-01-01"));
Assert.assertTrue(matcher.matches("2018-02-31"));
Assert.assertTrue(matcher.matches("2999-12-31"));
Assert.assertFalse(matcher.matches("1899-12-31"));
Assert.assertFalse(matcher.matches("2018-05-35"));
Assert.assertFalse(matcher.matches("2018-13-05"));
Assert.assertFalse(matcher.matches("3000-01-01"));
}
}

View File

@@ -0,0 +1,17 @@
package com.baeldung.regexp.datepattern.gregorian;
import com.baeldung.regexp.datepattern.DateMatcher;
import com.baeldung.regexp.datepattern.gregorian.testhelper.GregorianDateTestHelper;
import org.junit.Test;
public class February29thMatcherUnitTest {
private DateMatcher matcher = new February29thMatcher();
private GregorianDateTestHelper testHelper = new GregorianDateTestHelper(matcher);
@Test
public void whenYearIsLeap_thenYearHasFebruary29th() {
testHelper.assertFebruary29th();
}
}

View File

@@ -0,0 +1,17 @@
package com.baeldung.regexp.datepattern.gregorian;
import com.baeldung.regexp.datepattern.DateMatcher;
import com.baeldung.regexp.datepattern.gregorian.testhelper.GregorianDateTestHelper;
import org.junit.Test;
public class FebruaryGeneralMatcherUnitTest {
private DateMatcher matcher = new FebruaryGeneralMatcher();
private GregorianDateTestHelper testHelper = new GregorianDateTestHelper(matcher);
@Test
public void whenMonthIsFebruary_thenMonthContainsUpTo28Days() {
testHelper.assertFebruaryGeneralDates();
}
}

View File

@@ -0,0 +1,42 @@
package com.baeldung.regexp.datepattern.gregorian;
import com.baeldung.regexp.datepattern.DateMatcher;
import com.baeldung.regexp.datepattern.gregorian.testhelper.GregorianDateTestHelper;
import org.junit.Test;
public class GregorianDateMatcherUnitTest {
private DateMatcher matcher = new GregorianDateMatcher();
private GregorianDateTestHelper testHelper = new GregorianDateTestHelper(matcher);
@Test
public void whenUsingGregorianDateMatcher_thenFormatConstraintsSatisfied() {
testHelper.assertFormat();
}
@Test
public void whenUsingGregorianDateMatcher_thenRangeConstraintsSatisfied() {
testHelper.assertRange();
}
@Test
public void whenYearIsLeap_thenFebruaryHas29Days() {
testHelper.assertFebruary29th();
}
@Test
public void whenMonthIsFebruary_thenMonthContainsUpTo28Days() {
testHelper.assertFebruaryGeneralDates();
}
@Test
public void whenMonthIsShort_thenMonthContainsUpTo30Days() {
testHelper.assertMonthsOf30Days();
}
@Test
public void whenMonthIsLong_thenMonthContainsUpTo31Days() {
testHelper.assertMonthsOf31Dates();
}
}

View File

@@ -0,0 +1,17 @@
package com.baeldung.regexp.datepattern.gregorian;
import com.baeldung.regexp.datepattern.DateMatcher;
import com.baeldung.regexp.datepattern.gregorian.testhelper.GregorianDateTestHelper;
import org.junit.Test;
public class MonthsOf30DaysMatcherUnitTest {
private DateMatcher matcher = new MonthsOf30DaysMatcher();
private GregorianDateTestHelper testHelper = new GregorianDateTestHelper(matcher);
@Test
public void whenMonthIsShort_thenMonthContainsUpTo30Days() {
testHelper.assertMonthsOf30Days();
}
}

View File

@@ -0,0 +1,17 @@
package com.baeldung.regexp.datepattern.gregorian;
import com.baeldung.regexp.datepattern.DateMatcher;
import com.baeldung.regexp.datepattern.gregorian.testhelper.GregorianDateTestHelper;
import org.junit.Test;
public class MonthsOf31DaysMatcherUnitTest {
private DateMatcher matcher = new MonthsOf31DaysMatcher();
private GregorianDateTestHelper testHelper = new GregorianDateTestHelper(matcher);
@Test
public void whenMonthIsLong_thenMonthContainsUpTo31Days() {
testHelper.assertMonthsOf31Dates();
}
}

View File

@@ -0,0 +1,102 @@
package com.baeldung.regexp.datepattern.gregorian.testhelper;
import com.baeldung.regexp.datepattern.DateMatcher;
import org.junit.Assert;
public class GregorianDateTestHelper {
private final DateMatcher matcher;
public GregorianDateTestHelper(DateMatcher matcher) {
this.matcher = matcher;
}
public void assertFormat() {
Assert.assertTrue(matcher.matches("2017-12-31"));
Assert.assertTrue(matcher.matches("2018-01-01"));
Assert.assertFalse(matcher.matches("2018-02"));
Assert.assertFalse(matcher.matches("2018-02-01-01"));
Assert.assertFalse(matcher.matches("2018-02-XX"));
Assert.assertFalse(matcher.matches(" 2018-02-01"));
Assert.assertFalse(matcher.matches("2018-02-01 "));
Assert.assertFalse(matcher.matches("2020/02/28"));
Assert.assertFalse(matcher.matches("2020.02.29"));
}
public void assertRange() {
Assert.assertTrue(matcher.matches("1900-01-01"));
Assert.assertTrue(matcher.matches("2205-05-25"));
Assert.assertTrue(matcher.matches("2999-12-31"));
Assert.assertFalse(matcher.matches("1899-12-31"));
Assert.assertFalse(matcher.matches("2018-05-35"));
Assert.assertFalse(matcher.matches("2018-13-05"));
Assert.assertFalse(matcher.matches("3000-01-01"));
Assert.assertFalse(matcher.matches("3200-02-29"));
}
public void assertFebruary29th() {
Assert.assertTrue(matcher.matches("2000-02-29"));
Assert.assertTrue(matcher.matches("2400-02-29"));
Assert.assertTrue(matcher.matches("2800-02-29"));
Assert.assertTrue(matcher.matches("2020-02-29"));
Assert.assertTrue(matcher.matches("2024-02-29"));
Assert.assertTrue(matcher.matches("2028-02-29"));
Assert.assertFalse(matcher.matches("2017-02-29"));
Assert.assertFalse(matcher.matches("2018-02-29"));
Assert.assertFalse(matcher.matches("2019-02-29"));
Assert.assertFalse(matcher.matches("2100-02-29"));
Assert.assertFalse(matcher.matches("2200-02-29"));
Assert.assertFalse(matcher.matches("2300-02-29"));
}
public void assertFebruaryGeneralDates() {
Assert.assertTrue(matcher.matches("2018-02-01"));
Assert.assertTrue(matcher.matches("2019-02-13"));
Assert.assertTrue(matcher.matches("2020-02-25"));
Assert.assertFalse(matcher.matches("2000-02-30"));
Assert.assertFalse(matcher.matches("2400-02-62"));
Assert.assertFalse(matcher.matches("2420-02-94"));
}
public void assertMonthsOf30Days() {
Assert.assertTrue(matcher.matches("2018-04-30"));
Assert.assertTrue(matcher.matches("2019-06-30"));
Assert.assertTrue(matcher.matches("2020-09-30"));
Assert.assertTrue(matcher.matches("2021-11-30"));
Assert.assertTrue(matcher.matches("2022-04-02"));
Assert.assertTrue(matcher.matches("2023-06-14"));
Assert.assertTrue(matcher.matches("2024-09-26"));
Assert.assertFalse(matcher.matches("2018-04-31"));
Assert.assertFalse(matcher.matches("2019-06-31"));
Assert.assertFalse(matcher.matches("2020-09-31"));
Assert.assertFalse(matcher.matches("2021-11-31"));
Assert.assertFalse(matcher.matches("2022-04-32"));
Assert.assertFalse(matcher.matches("2023-06-64"));
Assert.assertFalse(matcher.matches("2024-09-96"));
}
public void assertMonthsOf31Dates() {
Assert.assertTrue(matcher.matches("2018-01-31"));
Assert.assertTrue(matcher.matches("2019-03-31"));
Assert.assertTrue(matcher.matches("2020-05-31"));
Assert.assertTrue(matcher.matches("2021-07-31"));
Assert.assertTrue(matcher.matches("2022-08-31"));
Assert.assertTrue(matcher.matches("2023-10-31"));
Assert.assertTrue(matcher.matches("2024-12-31"));
Assert.assertTrue(matcher.matches("2025-01-03"));
Assert.assertTrue(matcher.matches("2026-03-15"));
Assert.assertTrue(matcher.matches("2027-05-27"));
Assert.assertFalse(matcher.matches("2018-01-32"));
Assert.assertFalse(matcher.matches("2019-03-64"));
Assert.assertFalse(matcher.matches("2020-05-96"));
}
}

View File

@@ -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());
}
}

View File

@@ -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());
}
}

View File

@@ -0,0 +1,13 @@
*.class
#folders#
/target
/neoDb*
/data
/src/main/webapp/WEB-INF/classes
*/META-INF/*
# Packaged files #
*.jar
*.war
*.ear