How to perform elementary Date-Time calculations in Java 8
This quick Java Code tip shows how to perform the most commonly used and elementary Date-Time calculations viz. addition and subtraction of days, months, years, hours, minutes, seconds and nanoseconds when working with the new Java 8 classes
OUTPUT of the above code
Explanation of the code
java.time.LocalDate
, java.time.LocalTime
and java.time.LocalDateTime
.Java 8 code to perform Date-Time Calculations
package com.javabrahman.java8.time;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Month;
public class DateTimeCalculations {
public static void main(String args[]){
System.out.println("--------BASE LocalDate--------------");
LocalDate baseDate = LocalDate.of(2016, Month.JANUARY, 1);
System.out.println("Base Date: " + baseDate);
//Plus-Minus Days
System.out.println("--------PLUS-MINUS 10 DAYS--------");
LocalDate tenDaysLater = baseDate.plusDays(10);
System.out.println("Date after 10 days: " + tenDaysLater);
LocalDate tenDaysPrior = baseDate.minusDays(10);
System.out.println("Date before 10 days: " + tenDaysPrior);
//Plus-Minus Weeks
System.out.println("--------PLUS-MINUS 2 WEEKS-------");
LocalDate twoWeeksLater = baseDate.plusWeeks(2);
System.out.println("Date after 2 weeks: " + twoWeeksLater);
LocalDate twoWeeksPrior = baseDate.minusWeeks(2);
System.out.println("Date before 2 weeks: " + twoWeeksPrior);
//Plus-Minus Months
System.out.println("--------PLUS-MINUS 2 MONTHS-------");
LocalDate twoMonthsLater = baseDate.plusMonths(2);
System.out.println("Date after 2 months: " + twoMonthsLater);
LocalDate twoMonthsPrior = baseDate.minusMonths(2);
System.out.println("Date before 2 months: " + twoMonthsPrior);
//Plus-Minus Years
System.out.println("--------PLUS-MINUS 2 YEARS--------");
LocalDate twoYearsLater = baseDate.plusYears(2);
System.out.println("Date after 2 years: " + twoYearsLater);
LocalDate twoYearsPrior = baseDate.minusYears(2);
System.out.println("Date before 2 years: " + twoYearsPrior);
System.out.println("\n--------BASE LocalTime--------------");
LocalTime baseTime = LocalTime.of(10,00);
System.out.println("Base Time: " + baseTime);
//Plus-Minus Hours
System.out.println("--------PLUS-MINUS 10 HOURS-------");
LocalTime tenHoursLater = baseTime.plusHours(10);
System.out.println("Time after 10 hours: " + tenHoursLater);
LocalTime tenHoursPrior = baseTime.minusHours(10);
System.out.println("Time before 10 hours: " + tenHoursPrior);
//Plus-Minus Minutes
System.out.println("--------PLUS-MINUS 20 MINS-------");
LocalTime twentyMinsLater = baseTime.plusMinutes(20);
System.out.println("Time after 20 mins: " + twentyMinsLater);
LocalTime twentyMinsPrior = baseTime.minusMinutes(20);
System.out.println("Time before 20 mins: " + twentyMinsPrior);
System.out.println("\n----BASE LocalDateTime created out of baseDate & baseTime--");
LocalDateTime baseDateTime=LocalDateTime.of(baseDate,baseTime);
System.out.println("Base LocalDateTime: " + baseDateTime);
System.out.println("--------PLUS 10 HOURS-------");
LocalDateTime localDateTimePost10Hours = baseDateTime.plusHours(10);
System.out.println("Date-Time after 10 hours: " + localDateTimePost10Hours);
System.out.println("--------MINUS 2 DAYs-------");
LocalDateTime localDateTime2DaysPrior = baseDateTime.minusDays(2);
System.out.println("Date-Time before 2 days: " + localDateTime2DaysPrior);
}
}
--------BASE LocalDate-------------- Base Date: 2016-01-01 --------PLUS-MINUS 10 DAYS-------- Date after 10 days: 2016-01-11 Date before 10 days: 2015-12-22 --------PLUS-MINUS 2 WEEKS------- Date after 2 weeks: 2016-01-15 Date before 2 weeks: 2015-12-18 --------PLUS-MINUS 2 MONTHS------- Date after 2 months: 2016-03-01 Date before 2 months: 2015-11-01 --------PLUS-MINUS 2 YEARS-------- Date after 2 years: 2018-01-01 Date before 2 years: 2014-01-01 --------BASE LocalTime-------------- Base Time: 10:00 --------PLUS-MINUS 10 HOURS------- Time after 10 hours: 20:00 Time before 10 hours: 00:00 --------PLUS-MINUS 20 MINS------- Time after 20 mins: 10:20 Time before 20 mins: 09:40 ----BASE LocalDateTime created out of baseDate & baseTime-- Base LocalDateTime: 2016-01-01T10:00 --------PLUS 10 HOURS------- Date-Time after 10 hours: 2016-01-01T20:00 --------MINUS 2 DAYs------- Date-Time before 2 days: 2015-12-30T10:00
java.util.LocalDate
is Java8’s immutable date class without a timezone.- We create an instance of
LocalDate
, namedbaseDate
, using the staticof()
method with the value2016-January-01
. - The
toString()
method ofLocalDate
, which is used extensively, prints the date value in'uuuu-MM-dd'
format. LocalDate
provides methods for adding days (plusDays()
), weeks (plusWeeks()
), months (plusMonths()
) and years (plusYears()
). Internally, these methods create a copy of theLocalDate
object used to invoke these methods, adds the given number of days, weeks etc. and returns back the newly createdLocalDate
instance. The original instance remains unaffected by the addition operation.- Similar to addition methods,
LocalDate
provides subtraction methods -minusDays()
,minusWeeks()
,minusMonths()
andminusYears()
which like addition methods create a copy of the originalLocalDate
, perform the calculation and return back the newly createdLocalDate
object. - In the above code, addition and subtraction methods are invoked on the
baseDate
. java.time.LocalTime
class has atoString()
method returning time in one of the following formats -- HH:mm
- HH:mm:ss
- HH:mm:ss.SSS
- HH:mm:ss.SSSSSS
- HH:mm:ss.SSSSSSSSS
HH
is hours,mm
is minutes,ss
is seconds andSS
is for nanoseconds and is in varying length depending on accuracy required.
Note -toString()
method prints the shortest format possible depending on the constituent values provided while creating the object. The remaining constituents are assumed to be zero and not printed.- In the above code we create an instance of
LocalTime
, namedbaseTime
, using the staticof()
method by passing the hour and minute values to it. - Next we add and subtract hours and minutes from the baseTime using the
plusHours()
,minusHours()
,plusMinutes()
andminusMinutes()
methods. All of these methods return newLocalTime
instances after creating a copy of the originalLocalTime
instances on which the methods are invoked.
Note - There are 4 more methods -plusSeconds()
,minusSeconds()
,plusNanos()
andminusNanos()
which I have not shown above but can be used for second and nanosecond manipulations. - Next we create a
java.time.LocalDateTime
instance using the static methodof()
to which we pass the earlier createdbaseDate
andbaseTime
instances to initialize the object. LocalDateTime
class has atoString()
method returning local time in one of the following formats -- uuuu-MM-dd'T'HH:mm
- uuuu-MM-dd'T'HH:mm:ss
- uuuu-MM-dd'T'HH:mm:ss.SSS
- uuuu-MM-dd'T'HH:mm:ss.SSSSSS
- uuuu-MM-dd'T'HH:mm:ss.SSSSSSSSS
uuuu
is years,MM
is months,dd
is days,HH
is hours,mm
is minutes,ss
is seconds andSS
is for nanoseconds.
Note -toString()
method prints the shortest format possible depending on the constituent values provided while creating the object. The remaining constituents are assumed to be zero and not printed.LocalDateTime
provides addition and subtraction methods which are a union of the methods provided byLocalDate
andLocalTime
. All these methods return a new copy with the required arithmetical manipulations done.- I have shown two of the methods -
plusHours()
andminusDays()
. You can try the remaining methods as well.
Tutorials on Java 8’s new Date and Time API
Overview of Java 8's new Date and Time APIClick to Read Overview of Java 8's new Date-Time API Working with time zones in Java 8| ZonedDateTime, ZoneId tutorial with examplesClick to Read tutorial on time zone handling in Java 8 How to convert LocalDate to String and String to LocalDateClick to Read tutorial on String to LocalDate conversions How to convert java.util.Date to java.time.LocalDateClick to Read tutorial on java.util.Date to LocalDate conversion Formatting localized dates in Spanish and FrenchClick to Read date formatting in Spanish & French How to get day-of-week for a given dateHow to get day-of-week using java.time.DayOfWeek enumDate Modification using TemporalAdjuster Click to Read Tutorial on TemporalAdjusters
Overview of Java 8's new Date and Time APIClick to Read Overview of Java 8's new Date-Time API Working with time zones in Java 8| ZonedDateTime, ZoneId tutorial with examplesClick to Read tutorial on time zone handling in Java 8 How to convert LocalDate to String and String to LocalDateClick to Read tutorial on String to LocalDate conversions How to convert java.util.Date to java.time.LocalDateClick to Read tutorial on java.util.Date to LocalDate conversion Formatting localized dates in Spanish and FrenchClick to Read date formatting in Spanish & French How to get day-of-week for a given dateHow to get day-of-week using java.time.DayOfWeek enumDate Modification using TemporalAdjuster Click to Read Tutorial on TemporalAdjusters