Skip to main content Link Menu Expand (external link) Document Search Copy Copied

Calculating with dates and times: Adding and subtracting time

Header Image

Ahoy there mateys! As we navigate the treacherous waters of time and date calculations, it’s important to have a reliable compass to guide us. Luckily, the Java DateTime library provides us with the tools we need to stay on course. In this article, we’ll focus on one of the most important calculations we can make with dates and times: adding and subtracting time.

Adding and subtracting time

Have you ever wished for a time machine to go back and relive a particular moment, or fast forward to the future to see what’s in store? While we can’t provide you with a TARDIS, we can show you how to add or subtract time from a given date or time.

Let’s start with a simple example. Suppose you’re planning a voyage and you want to know what the date and time will be exactly one month from today. With the Java DateTime library, we can accomplish this with just a few lines of code:

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

// get the current date and time
LocalDateTime now = LocalDateTime.now();

// add one month
LocalDateTime oneMonthLater = now.plusMonths(1);

// format the date and time using a pattern
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM d, yyyy h:mm a");
String formatted = oneMonthLater.format(formatter);

// print the result
System.out.println("One month from now it will be " + formatted);

In this example, we start by getting the current date and time using the LocalDateTime.now() method. We then add one month to this date and time using the plusMonths() method. Finally, we format the resulting date and time using a custom pattern and print it to the console. The output might look something like this:

One month from now it will be Jun 26, 2023 10:15 AM

As you can see, adding or subtracting time from a date or time is a simple matter of calling the appropriate method and passing in the desired value. The Java DateTime library provides a wide variety of methods for adding or subtracting time, including plusYears(), plusMonths(), plusWeeks(), plusDays(), plusHours(), plusMinutes(), plusSeconds(), and plusNanos(). Similarly, there are corresponding methods for subtracting time, such as minusYears(), minusMonths(), minusWeeks(), and so on.

Working with durations

Adding or subtracting time is just one aspect of working with dates and times. Another important concept is duration, which represents the amount of time between two points in time. Suppose you’re trying to calculate how many hours you have until the next high tide. With the Java DateTime library, we can calculate the duration between two date and time values like this:

import java.time.LocalDateTime;
import java.time.Duration;

// get the current date and time
LocalDateTime now = LocalDateTime.now();

// set the high tide date and time
LocalDateTime highTide = LocalDateTime.of(2023, 4, 27, 6, 30);

// calculate the duration between now and high tide
Duration duration = Duration.between(now, highTide);

// get the number of hours until high tide
long hours = duration.toHours();

// print the result
System.out.println("There are " + hours + " hours until high tide.");

In this example, we start by getting the current date and time using LocalDateTime.now(). We then set the date and time for the nexthigh tide using the LocalDateTime.of() method. We then calculate the duration between the two date and time values using the Duration.between() method, which returns a Duration object representing the time between the two values. Finally, we convert the duration to hours using the toHours() method and print the result to the console. The output might look something like this:

There are 14 hours until high tide.

As you can see, working with durations is a powerful way to calculate the time between two points in time, and the Java DateTime library provides us with a simple and intuitive way to do so.

Conclusion

Adding or subtracting time and working with durations are just two examples of the many ways in which the Java DateTime library can help us navigate the tricky waters of date and time calculations. By using the tools provided by the library, we can perform complex calculations with ease and confidence, ensuring that we always stay on course. So next time you need to calculate the time between two events or add or subtract time from a date or time value, reach for your trusty Java DateTime library and set sail with confidence!

high tide using the LocalDateTime.of() method. We calculate the duration between the two date and time values using Duration.between(), and then convert the duration to hours using the toHours() method. Finally, we print the result to the console.

The Java DateTime library provides a variety of methods for working with durations, including toDays(), toHours(), toMinutes(), toSeconds(), and toNanos(). There are also methods for creating durations directly, such as Duration.ofDays(), Duration.ofHours(), and so on.

Obtaining time between two dates

In addition to calculating the duration between two date and time values, we may also want to know the number of days, months, or years between two dates. The Java DateTime library provides a separate class, Period, specifically for working with date-based amounts of time. Let’s take a look at an example:

import java.time.LocalDate;
import java.time.Period;

// set the start and end dates
LocalDate start = LocalDate.of(2023, 4, 1);
LocalDate end = LocalDate.of(2023, 4, 26);

// calculate the period between the two dates
Period period = Period.between(start, end);

// get the number of days, months, and years between the two dates
int days = period.getDays();
int months = period.getMonths();
int years = period.getYears();

// print the result
System.out.println("There are " + years + " years, " + months + " months, and " + days + " days between " + start + " and " + end + ".");

In this example, we set the start and end dates using LocalDate.of(), and then calculate the period between the two dates using Period.between(). We then extract the number of days, months, and years using the getDays(), getMonths(), and getYears() methods, respectively. Finally, we print the result to the console. The output might look something like this:

There are 0 years, 0 months, and 25 days between 2023-04-01 and 2023-04-26.

As you can see, obtaining the time between two dates is a simple matter of using the Period class and its associated methods. The Period class provides a wide range of functionality for working with date-based periods, including methods for creating periods directly, such as Period.ofDays(), Period.ofMonths(), and so on.

That’s all for now, mateys! We hope this article has helped you navigate the choppy waters of date and time calculations. Remember, the Java DateTime library provides a wide variety of tools for working with dates, times, durations, and periods, so don’t be afraid to explore all the options available to you. Until next time, happy coding!

Working with durations

In addition to calculating the duration between two date and time values, we can also perform arithmetic operations with durations. For example, we may want to know the date and time that is three hours and fifteen minutes after the current date and time. With the Java DateTime library, we can do this as follows:

import java.time.LocalDateTime;
import java.time.Duration;

// get the current date and time
LocalDateTime now = LocalDateTime.now();

// define the duration to add
Duration duration = Duration.ofHours(3).plusMinutes(15);

// add the duration to the current date and time
LocalDateTime result = now.plus(duration);

// print the result
System.out.println("Three hours and fifteen minutes from now it will be " + result);

In this example, we start by getting the current date and time using LocalDateTime.now(). We then define a duration of three hours and fifteen minutes using Duration.ofHours() and Duration.plusMinutes(). We add this duration to the current date and time using LocalDateTime.plus(), and then print the result to the console. The output might look something like this:

Three hours and fifteen minutes from now it will be 2023-04-26T13:30:15.123456789

As you can see, working with durations allows us to perform complex date and time calculations with ease. The Java DateTime library provides a wide range of methods for creating and manipulating durations, including ofDays(), ofHours(), ofMinutes(), ofSeconds(), and ofNanos(). There are also methods for performing arithmetic operations with durations, such as plus(), minus(), multipliedBy(), and dividedBy().

Conclusion

Well, me hearties, we’ve reached the end of our journey through the Java DateTime library. We hope you’ve found this article helpful in navigating the sometimes-tricky waters of dates and times. Remember, the Java DateTime library provides a powerful set of tools for working with dates, times, durations, and periods, and can help you steer a steady course through even the stormiest seas of date and time calculations. Until next time, fair winds and following seas!