Reader small image

You're reading from  Java Coding Problems - Second Edition

Product typeBook
Published inMar 2024
PublisherPackt
ISBN-139781837633944
Edition2nd Edition
Right arrow
Author (1)
Anghel Leonard
Anghel Leonard
author image
Anghel Leonard

Anghel Leonard is a Chief Technology Strategist and independent consultant with 20+ years of experience in the Java ecosystem. In daily work, he is focused on architecting and developing Java distributed applications that empower robust architectures, clean code, and high-performance. Also passionate about coaching, mentoring and technical leadership. He is the author of several books, videos and dozens of articles related to Java technologies.
Read more about Anghel Leonard

Right arrow

74. Getting the first and last day of a quarter

Let’s assume that we represent the first and last day of a quarter via this simple class:

public final class Quarter {
  private final Date firstDay;
  private final Date lastDay;
  ...
}

Next, we have a java.util.Date and we want the first and the last day of the quarter containing this date. For this, we can use JDK 8’s IsoFields.DAY_OF_QUARTER (we introduced IsoFields in the previous problem). But, before we can use IsoFields, we have to convert the given java.util.Date to a LocalDate as follows:

LocalDate localDate = date.toInstant()
  .atZone(ZoneId.systemDefault()).toLocalDate();

Once we have the given Date as a LocalDate, we can easily extract the first day of the quarter via IsoFields.DAY_OF_QUARTER. Next, we add 2 months to this day to move into the last month of the quarter (a quarter has 3 months, so a year has 4 quarters) and we rely on java.time.temporal.TemporalAdjusters, more precisely on...

lock icon
The rest of the page is locked
Previous PageNext Page
You have been reading a chapter from
Java Coding Problems - Second Edition
Published in: Mar 2024Publisher: PacktISBN-13: 9781837633944

Author (1)

author image
Anghel Leonard

Anghel Leonard is a Chief Technology Strategist and independent consultant with 20+ years of experience in the Java ecosystem. In daily work, he is focused on architecting and developing Java distributed applications that empower robust architectures, clean code, and high-performance. Also passionate about coaching, mentoring and technical leadership. He is the author of several books, videos and dozens of articles related to Java technologies.
Read more about Anghel Leonard