Files
java-tutorials/java-difference-date/src/test/java/com/baeldung/DateDiffTest.java
T

61 lines
1.9 KiB
Java
Raw Normal View History

2017-08-24 21:04:23 +01:00
package com.baeldung;
import org.joda.time.DateTime;
import org.junit.Test;
import java.text.ParseException;
import java.text.SimpleDateFormat;
2017-08-25 09:46:35 +01:00
import java.time.Duration;
2017-08-24 21:04:23 +01:00
import java.time.ZonedDateTime;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
2017-08-25 09:46:35 +01:00
import java.util.concurrent.TimeUnit;
2017-08-24 21:04:23 +01:00
import static org.junit.Assert.assertEquals;
public class DateDiffTest {
@Test
2017-08-25 09:46:35 +01:00
public void givenTwoDatesBeforeJava8_whenDifferentiating_thenWeGetSix() throws ParseException {
2017-08-24 21:04:23 +01:00
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy", Locale.ENGLISH);
Date firstDate = sdf.parse("06/24/2017");
Date secondDate = sdf.parse("06/30/2017");
2017-08-25 09:46:35 +01:00
long diffInMillies = Math.abs(secondDate.getTime() - firstDate.getTime());
long diff = TimeUnit.DAYS.convert(diffInMillies, TimeUnit.MILLISECONDS);
2017-08-24 21:04:23 +01:00
assertEquals(diff, 6);
}
@Test
2017-08-25 09:46:35 +01:00
public void givenTwoDatesInJava8_whenDifferentiating_thenWeGetSix() {
2017-08-24 21:04:23 +01:00
ZonedDateTime now = ZonedDateTime.now();
ZonedDateTime sixDaysBehind = now.minusDays(6);
2017-08-25 09:46:35 +01:00
Duration duration = Duration.between(now, sixDaysBehind);
long diff = Math.abs(duration.toDays());
2017-08-24 21:04:23 +01:00
assertEquals(diff, 6);
}
@Test
2017-08-25 09:46:35 +01:00
public void givenTwoDatesInJodaTime_whenDifferentiating_thenWeGetSix() {
2017-08-24 21:04:23 +01:00
DateTime now = DateTime.now();
DateTime sixDaysBehind = now.minusDays(6);
2017-08-25 09:46:35 +01:00
org.joda.time.Duration duration = new org.joda.time.Duration(now, sixDaysBehind);
long diff = Math.abs(duration.getStandardDays());
2017-08-24 21:04:23 +01:00
assertEquals(diff, 6);
}
@Test
2017-08-25 09:46:35 +01:00
public void givenTwoDatesInDate4j_whenDifferentiating_thenWeGetSix() {
2017-08-24 21:04:23 +01:00
hirondelle.date4j.DateTime now = hirondelle.date4j.DateTime.now(TimeZone.getDefault());
hirondelle.date4j.DateTime sixDaysBehind = now.minusDays(6);
2017-08-25 09:46:35 +01:00
long diff = Math.abs(now.numDaysFrom(sixDaysBehind));
2017-08-24 21:04:23 +01:00
assertEquals(diff, 6);
}
}