How to Subtract Dates in Java

Subtract two dates in Java

Edit 2018-05-28
I have changed the example to use Java 8's Time API:

LocalDate d1 = LocalDate.parse("2018-05-26", DateTimeFormatter.ISO_LOCAL_DATE);
LocalDate d2 = LocalDate.parse("2018-05-28", DateTimeFormatter.ISO_LOCAL_DATE);
Duration diff = Duration.between(d1.atStartOfDay(), d2.atStartOfDay());
long diffDays = diff.toDays();

Java: Easiest Way to Subtract Dates

tl;dr

To move from one date to another by adding/subtracting a number of days.

LocalDate.now(
ZoneId.of( "Pacific/Auckland" )
)
.minusDays( 5 )

To calculate the number of days, months, and years elapsed between two dates.

ChronoUnit.DAYS.between( start , stop )

Parsing

First you must parse your string inputs into date-time objects. Then you work on preforming your business logic with those objects.

Stop thinking of date-time values as strings, that will drive you nuts. We work with date-time objects in our code; we exchange data with users or other apps using a String representation of that date-time object.

In Java 8 and later, use the java.time framework. See Tutorial.

You want only a date, without time-of-day, so we can use the LocalDate class.

That funky double-colon syntax is a method reference, a way to say what method should be called by other code.

String input = "2015 01 02";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern ( "yyyy MM dd" );
LocalDate localDate = formatter.parse ( input , LocalDate :: from );

Current date

Determining today’s date requires a time zone. For any given moment, the date varies around the globe by zone.

ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
LocalDate todayTunis = LocalDate.now( z ) ;

If you want the JVM’s current default time zone, call ZoneId.systemDefault.

Subtracting Dates

This has been addressed many times before on StackOveflow.com. For example, How to subtract X days from a date using Java calendar?. For details, see other Answers such as this one by me and this one by me for more details. Tip: "elapsed" is a key search word.

Use ChronoUnit.DAYS enum to calculate count of days elapsed.

LocalDate weekLater = localDate.plusDays ( 7 );
long daysElapsed = java.time.temporal.ChronoUnit.DAYS.between( todayTunis , weekLater ) ;

Dump to console.

System.out.println ( "localDate: " + localDate + " to " + weekLater + " in days: " + daysElapsed );

localDate: 2015-01-02 to 2015-01-09 in days: 7

How to subtract X day from a Date object in Java?

Java 8 and later

With Java 8's date time API change, Use LocalDate

LocalDate date = LocalDate.now().minusDays(300);

Similarly you can have

LocalDate date = someLocalDateInstance.minusDays(300);

Refer to https://stackoverflow.com/a/23885950/260990 for translation between java.util.Date <--> java.time.LocalDateTime

Date in = new Date();
LocalDateTime ldt = LocalDateTime.ofInstant(in.toInstant(), ZoneId.systemDefault());
Date out = Date.from(ldt.atZone(ZoneId.systemDefault()).toInstant());

Java 7 and earlier

Use Calendar's add() method

Calendar cal = Calendar.getInstance();
cal.setTime(dateInstance);
cal.add(Calendar.DATE, -30);
Date dateBefore30Days = cal.getTime();

How do you subtract Dates in Java?

It's indeed one of the biggest epic failures in the standard Java API. Have a bit of patience, then you'll get your solution in flavor of the new Date and Time API specified by JSR 310 / ThreeTen which is (most likely) going to be included in the upcoming Java 8.

Until then, you can get away with JodaTime.

DateTime dt1 = new DateTime(2000, 1, 1, 0, 0, 0, 0);
DateTime dt2 = new DateTime(2010, 1, 1, 0, 0, 0, 0);
int days = Days.daysBetween(dt1, dt2).getDays();

Its creator, Stephen Colebourne, is by the way the guy behind JSR 310, so it'll look much similar.

Calculate date/time difference in java

try

long diffSeconds = diff / 1000 % 60;  
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000);

NOTE: this assumes that diff is non-negative.

Calculating the difference between two Java date instances

The JDK Date API is horribly broken unfortunately. I recommend using Joda Time library.

Joda Time has a concept of time Interval:

Interval interval = new Interval(oldTime, new Instant());

EDIT: By the way, Joda has two concepts: Interval for representing an interval of time between two time instants (represent time between 8am and 10am), and a Duration that represents a length of time without the actual time boundaries (e.g. represent two hours!)

If you only care about time comparisions, most Date implementations (including the JDK one) implements Comparable interface which allows you to use the Comparable.compareTo()

Addition and Subtraction of Dates in Java

First of all you have to convert your String date to java.util.Date, than you have to use java.util.Calendar to manipulate dates. It is also possible to do math with millis, but I do not recommend this.

public static void main( final String[] args ) throws ParseException {
final String sdate = "2012-01-01";
final SimpleDateFormat df = new SimpleDateFormat( "yyyy-MM-dd" );
final Date date = df.parse( sdate ); // conversion from String
final java.util.Calendar cal = GregorianCalendar.getInstance();
cal.setTime( date );
cal.add( GregorianCalendar.MONTH, 5 ); // date manipulation
System.out.println( "result: " + df.format( cal.getTime() ) ); // conversion to String
}


Related Topics



Leave a reply



Submit