The following code snippet shows you a various way to get the quarter of a given date. Some methods that we use below are:
- Using the new
java.time
API of Java 8IsoFields.QUARTER_OF_YEAR
. - Using Java 8
DateTimeFormatter
pattern of Q or q. The length of “q” give us a different result. - Using
java.util.Date
. - Using
java.util.Calendar
. - Get the quarter from an array of string.
Let’s see the code snippet in action.
package org.kodejava.datetime;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.IsoFields;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
public class DateQuarter {
public static void main(String[] args) {
// Using Java 8
LocalDate now = LocalDate.now();
int quarter = now.get(IsoFields.QUARTER_OF_YEAR);
System.out.println("quarter = " + quarter);
// Using DateTimeFormatter Q / q, set the Locale to get value
// in local format
String quarter1 = LocalDate.of(2023, 8, 17)
.format(DateTimeFormatter.ofPattern("q", Locale.US));
String quarter2 = LocalDate.of(2023, 8, 17)
.format(DateTimeFormatter.ofPattern("qq", Locale.US));
String quarter3 = LocalDate.of(2023, 8, 17)
.format(DateTimeFormatter.ofPattern("qqq", Locale.US));
String quarter4 = LocalDate.of(2023, 8, 17)
.format(DateTimeFormatter.ofPattern("qqqq", Locale.US));
System.out.println("quarter1 = " + quarter1);
System.out.println("quarter2 = " + quarter2);
System.out.println("quarter3 = " + quarter3);
System.out.println("quarter4 = " + quarter4);
// Using older version of Java
Date today = new Date();
quarter = (today.getMonth() / 3) + 1;
System.out.println("quarter = " + quarter);
// Using java.util.Calendar object. For certain date
// we can set the calendar date using setTime() method.
Calendar calendar = Calendar.getInstance();
quarter = (calendar.get(Calendar.MONTH) / 3) + 1;
System.out.println("quarter = " + quarter);
// Custom the quarter as text
String[] quarters = new String[]{"Q1", "Q2", "Q3", "Q4"};
String quarterString = quarters[quarter - 1];
System.out.println("quarterString = " + quarterString);
}
}
And here are the result of the code snippet above:
quarter = 1
quarter1 = 3
quarter2 = 03
quarter3 = Q3
quarter4 = 3rd quarter
quarter = 1
quarter = 1
quarterString = Q1
Latest posts by Wayan (see all)
- How do I create a string of repeated characters? - September 1, 2023
- How do I convert datetime string with optional part to a date object? - August 28, 2023
- How do I split large excel file into multiple smaller files? - April 15, 2023