[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
@@ -1,70 +0,0 @@
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);
}
}
@@ -1,141 +0,0 @@
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));
}
}
@@ -1,186 +0,0 @@
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());
}
}