1

I am looking to support quarters and weeks as objects in my Java code.

I am aware that the troublesome old legacy date-time classes in Java have been supplanted by the modern java.time classes. But I do not see any “Quarter” or “Week” classes amongst the classes such as LocalDate and Instant.

1

ThreeTen-Extra

Yes, there is such a library to represent:

  • Quarters
    If you mean quarters # 1 = January-March, # 2 = April-June, and so on.
  • Weeks
    If you mean weeks according to the ISO 8601 standard week, where week number one of the week-based-year contains the first Thursday of the calendar-year, starts on a Monday and runs through Sunday, for a total of 52 or 53 weeks per year.

In those definitions meet yours, then add the ThreeTen-Extra library to your project.

Look at classes:

java.time

The java.time classes built into Java 8 & 9 offer limited support for week and year of a week-based-year.

IsoFields

Use get method and pass one of the IsoFields constants. Call get on various classes such as ZonedDateTime and LocalDate.

myZonedDateTime.get( IsoFields.WEEK_OF_WEEK_BASED_YEAR )
myZonedDateTime.get( IsoFields.WEEK_BASED_YEAR )

DateTimeFormatter

Also, the DateTimeFormatter class includes some formatting code for both values week and week-based-year. You can put them together for ISO 8601 standard format of “yyyy-Www”.

DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu-'W'ww" ) ;
String output = LocalDate.now().format( f );

2018-W39

For the full version of the standard format that appends the day-of-week as a digit 1-7 for Monday-Sunday, use the predefined constant, DateTimeFormatter.ISO_WEEK_DATE.

DateTimeFormatter f = DateTimeFormatter.ISO_WEEK_DATE ;  // yyyy-Www-d  For example: 2018-W39-7
String output = LocalDate.now().format( f );

2018-W39-7


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Using a JDBC driver compliant with JDBC 4.2 or later, you may exchange java.time objects directly with your database. No need for strings nor java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.