Java - Add / Subtract date time

By xngo on June 15, 2019

With the new Date and Time APIs provided in Java 8, adding and subtracting date time have never been easier. Here are some examples using LocalDateTime.

package net.openwritings.java.time;
 
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
 
public class AddSubDateTime {
 
    public static void main(String[] args) {
 
        // Get today date time.
        LocalDateTime today = LocalDateTime.now();
        System.out.println("today = " + today.toString());
 
        // Additions.
        System.out.println(" 2 seconds later = " + today.plusSeconds(2).toString());
        System.out.println(" 3 mintues later = " + today.plusMinutes(3).toString());
        System.out.println(" 5 hours   later = " + today.plusHours(5).toString());
        System.out.println(" 7 days    later = " + today.plusDays(7).toString());
        System.out.println(" 5 weeks   later = " + today.plusWeeks(5).toString());
        System.out.println(" 9 months  later = " + today.plusMonths(9).toString());
        System.out.println("10 years   later = " + today.plusYears(10).toString());
 
        // Subtractions.
        System.out.println(" 2 seconds ago = " + today.minusSeconds(2).toString());
        System.out.println(" 3 mintues ago = " + today.minusMinutes(3).toString());
        System.out.println(" 5 hours   ago = " + today.minusHours(5).toString());
        System.out.println(" 7 days    ago = " + today.minusDays(7).toString());
        System.out.println(" 5 weeks   ago = " + today.minusWeeks(5).toString());
        System.out.println(" 9 months  ago = " + today.minusMonths(9).toString());
        System.out.println("10 years   ago = " + today.minusYears(10).toString());
 
        // Get the different between 2 dates.
        LocalDateTime tomorrow = today.plusDays(1);
        long minutes = ChronoUnit.MINUTES.between(today, tomorrow);
        System.out.println("Number of minutes between today & tomorrow is: " + minutes);
    }
 
}

Output

today = 2019-06-15T18:14:16.425
 2 seconds later = 2019-06-15T18:14:18.425
 3 mintues later = 2019-06-15T18:17:16.425
 5 hours   later = 2019-06-15T23:14:16.425
 7 days    later = 2019-06-22T18:14:16.425
 5 weeks   later = 2019-07-20T18:14:16.425
 9 months  later = 2020-03-15T18:14:16.425
10 years   later = 2029-06-15T18:14:16.425
 2 seconds ago = 2019-06-15T18:14:14.425
 3 mintues ago = 2019-06-15T18:11:16.425
 5 hours   ago = 2019-06-15T13:14:16.425
 7 days    ago = 2019-06-08T18:14:16.425
 5 weeks   ago = 2019-05-11T18:14:16.425
 9 months  ago = 2018-09-15T18:14:16.425
10 years   ago = 2009-06-15T18:14:16.425
Number of minutes between today & tomorrow is: 1440

Github

  • https://github.com/xuanngo2001/java-small/blob/master/src/net/openwritings/java/time/AddSubDateTime.java

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.