Working with Dates in Java

Marcos
Javarevisited
Published in
3 min readJan 15, 2022

--

Working with dates has always been a bit complex, whoever used Date and Calendar understands this well. But in Java 8 LocalDate was included, inside the java.time package, and that brought a lot of static methods that make life easier.

The documentation is here:

https://docs.oracle.com/javase/8/docs/api/java/time/LocalDateTime.html

Getting today’s date:

LocalDate today = LocalDate.now();
System.out.println(today);

Simple.

Calculating a period in years

How many years have passed since the last football world cup?

LocalDate today = LocalDate.now();
LocalDate worldCupDate = LocalDate.of(2018, Month.JUNE, 5);
int years = worldCupDate.getYear() - today.getYear();
System.out.println(years + " years");

Calculating a period in days and months

This one is really cool:

Period period = Period.between(today, worldCupDate);
System.out.println(period);

Just pass two dates. Result:

  • 3Y = 3 years
  • 2M = 2 months
  • 29D = 29 days

Formatting dates

I’ll put it in the Brazilian standard, but it works for several others:

DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
System.out.println(today.format(dateTimeFormatter));

Incrementing or decrementing dates

System.out.println(today.minusYears(1));
System.out.println(today.minusMonths(4));
System.out.println(today.minusDays(2));

System.out.println(today.plusYears(1));
System.out.println(today.plusMonths(4));
System.out.println(today.plusDays(2));

But what if I want an hour, minute, and second?

Then the class changes, for that we can use the LocalDateTime and its usage is very similar:

LocalDateTime now = LocalDateTime.now();
System.out.println(now);

We can also format:

DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss");

LocalDateTime now = LocalDateTime.now();
System.out.println(now.format(dateTimeFormatter));

And the result is that:

LocalTime

We can work only with time periods to represent times of some activity, for example, the time of a football game:

LocalTime hourOfGame= LocalTime.of(16, 30);
System.out.println(hourOfGame);

The most interesting part so far is that we didn’t make any calculations with the dates, we just asked the API and it did it for us. That’s great.

How to get a range in days?

I’ve seen several solutions on forums, with many lines of code and all the work done by hand. I know how to do it, and most likely you do too, but there is a slightly simpler way:

public static void main(String[] args) {
LocalDate date1 = LocalDate.of(2018, Month.JUNE, 5);
var numberOfDays = ChronoUnit.DAYS.between(date1, LocalDate.now());
System.out.println(numberOfDays);
}

And the result:

That’s it for today.

--

--

Marcos
Javarevisited

I study software development and I love memes.