How do I discover the quarter of a given date?

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 8 IsoFields.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

How do I get the first Sunday of the year in Java?

The following code snippet help you find the first Sunday of the year, or you can replace it with any day that you want. To achieve this we can use the TemporalAdjusters.firstInMonth adjusters, these adjusters returns a new date in the same month with the first matching day-of-week. This is used for expressions like ‘first Sunday in January’.

Because we want to get the first Sunday of the year first we create a LocalDate which represent the 1st January 2020. Then we call the with() method and pass the firstInMonth adjusters with the DayOfWeek.SUNDAY to find. Beside using Java 8 date time API, you can also use the old java.util.Calendar class as also shown in the code snippet below. But using the new date time API give you a more readable, simpler and less code to write.

package org.kodejava.datetime;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.Month;
import java.time.ZoneId;
import java.util.Calendar;

import static java.time.temporal.TemporalAdjusters.firstInMonth;

public class FirstSundayOfTheYear {
    public static void main(String[] args) {
        // Get the first Sunday of the year using Java 8 date time
        LocalDate now = LocalDate.of(2020, Month.JANUARY, 1);
        LocalDate sunday = now.with(firstInMonth(DayOfWeek.SUNDAY));
        System.out.println("The first Sunday of 2020 falls on: " + sunday);

        // Get the first Sunday of the year using the old java.util.Calendar
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
        calendar.set(Calendar.DAY_OF_WEEK_IN_MONTH, 1);
        calendar.set(Calendar.MONTH, Calendar.JANUARY);
        calendar.set(Calendar.YEAR, 2020);
        System.out.println("The first Sunday of 2020 falls on: " + calendar.getTime());
        System.out.println("The first Sunday of 2020 falls on: " +
                LocalDate.ofInstant(calendar.getTime().toInstant(), ZoneId.systemDefault()));
    }
}

This code snippet will print out the following output:

The first Sunday of 2020 falls on: 2020-01-05
The first Sunday of 2020 falls on: Sun Jan 05 22:43:37 CST 2020
The first Sunday of 2020 falls on: 2020-01-05

How do I set the time of java.util.Date instance to 00:00:00?

The following code snippet shows you how to remove time information from the java.util.Date object. The static method removeTime() in the code snippet below will take a Date object as parameter and will return a new Date object where the hour, minute, second and millisecond information hasbeen reset to zero. To do this, we use the java.util.Calendar. To remove time information, we set the calendar fields of Calendar.HOUR_OF_DAY, Calendar.MINUTE, Calendar.SECOND and Calendar.MILLISECOND to zero.

package org.kodejava.util;

import java.util.Calendar;
import java.util.Date;

public class DateRemoveTime {
    public static void main(String[] args) {
        System.out.println("Now = " + removeTime(new Date()));
    }

    private static Date removeTime(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTime();
    }
}

The result of the code snippet above is:

Now = Sat Nov 20 00:00:00 CST 2021

In the above code:

  1. An instance of Calendar is created using Calendar.getInstance().
  2. We set the Calendar time using setTime() method and pass the date object.
  3. The time fields (HOUR_OF_DAY, MINUTE, SECOND, MILLISECOND) are set to zero. Calendar.HOUR_OF_DAY is used for 24-hour clock.
  4. The resulting Calendar instances time value is printed which should now represent the start of the day.

How do I convert between old Date and Calendar object with the new Java 8 Date Time?

In this example we will learn how to convert the old java.util.Date and java.util.Calendar objects to the new Date Time introduced in Java 8. The first method in the code snippet below dateToNewDate() show conversion of java.util.Date while the calendarToNewDate() show the conversion of java.util.Calendar.

The java.util.Date and java.util.Calendar provide a toInstant() method to convert the objects to the new Date Time API class of the java.time.Instant. To convert the old date into the Java 8 LocalDate, LocalTime and LocalDateTime we first can create an instance of ZonedDateTime using the atZone() method of the Instant class.

ZonedDateTime zonedDateTime = instant.atZone(ZoneId.systemDefault());

From an instance of ZonedDateTime class we can call the toLocalDate(), toLocalTime() and toLocalDateTime() to get instance of LocalDate, LocalTime and LocalDateTime.

To convert back from the new Java 8 date to the old java.util.Date we can use the Date.from() static factory method and passing and instance of java.time.Instant that we can obtain by calling the following code.

Instant instant1 = dateTime.atZone(ZoneId.systemDefault()).toInstant();
Date now1 = Date.from(instant1);

Here are the complete code snippet to convert java.util.Date to the new Java 8 Date Time.

private static void dateToNewDate() {
    Date now = new Date();
    Instant instant = now.toInstant();

    ZonedDateTime zonedDateTime = instant.atZone(ZoneId.systemDefault());

    LocalDate date = zonedDateTime.toLocalDate();
    LocalTime time = zonedDateTime.toLocalTime();
    LocalDateTime dateTime = zonedDateTime.toLocalDateTime();

    Instant instant1 = dateTime.atZone(ZoneId.systemDefault()).toInstant();
    Date now1 = Date.from(instant1);

    System.out.println("java.util.Date          = " + now);
    System.out.println("java.time.LocalDate     = " + date);
    System.out.println("java.time.LocalTime     = " + time);
    System.out.println("java.time.LocalDateTime = " + dateTime);
    System.out.println("java.util.Date          = " + now1);
    System.out.println();
}

The steps for converting from the java.util.Calendar to the new Java 8 date can be seen in the code snippet below. As with java.util.Date the Calendar class provide toInstant() method to convert the calendar to java.time.Instant object.

Using the LocalDateTime.ofInstant() method we can create a LocalDateTime object from the instant object. By having the LocalDateTime object we can then get an instance of LocalDate and LocalTime by calling the toLocalDate() and toLocalTime() method.

Finally, to convert back to java.util.Calendar we can use the GregorianCalendar.from() static factory method which require an instance of ZonedDateTime to be passed as a parameter. To get an instance of ZonedDateTime we can call LocalDateTime.atZone() method. You can see the complete code in the code snippet below.

private static void calendarToNewDate() {
    Calendar now = Calendar.getInstance();

    LocalDateTime dateTime = LocalDateTime.ofInstant(now.toInstant(),
            ZoneId.systemDefault());

    LocalDate date = dateTime.toLocalDate();
    LocalTime time = dateTime.toLocalTime();

    ZonedDateTime zonedDateTime = dateTime.atZone(ZoneId.systemDefault());
    Calendar now1 = GregorianCalendar.from(zonedDateTime);

    System.out.println("java.util.Calendar      = " + now);
    System.out.println("java.time.LocalDateTime = " + dateTime);
    System.out.println("java.time.LocalDate     = " + date);
    System.out.println("java.time.LocalTime     = " + time);
    System.out.println("java.util.Calendar      = " + now1);
}

Below is the main Java class to run the code snippet. You must place the above methods inside this class to run the code snippet.

package org.kodejava.datetime;

import java.time.*;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

public class LegacyDateCalendarToNewDateExample {
    public static void main(String[] args) {
        dateToNewDate();
        calendarToNewDate();
    }
}

Here are the result of the code snippet above. The first group is conversion the java.util.Date to the new Date Time API. The second group is conversion from the java.util.Calendar to the new Date Time API.

java.util.Date          = Tue Nov 16 08:44:51 CST 2021
java.time.LocalDate     = 2021-11-16
java.time.LocalTime     = 08:44:51.031
java.time.LocalDateTime = 2021-11-16T08:44:51.031
java.util.Date          = Tue Nov 16 08:44:51 CST 2021

java.util.Calendar      = java.util.GregorianCalendar[time=1637023491089,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Asia/Shanghai",offset=28800000,dstSavings=0,useDaylight=false,transitions=31,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2021,MONTH=10,WEEK_OF_YEAR=47,WEEK_OF_MONTH=3,DAY_OF_MONTH=16,DAY_OF_YEAR=320,DAY_OF_WEEK=3,DAY_OF_WEEK_IN_MONTH=3,AM_PM=0,HOUR=8,HOUR_OF_DAY=8,MINUTE=44,SECOND=51,MILLISECOND=89,ZONE_OFFSET=28800000,DST_OFFSET=0]
java.time.LocalDateTime = 2021-11-16T08:44:51.089
java.time.LocalDate     = 2021-11-16
java.time.LocalTime     = 08:44:51.089
java.util.Calendar      = java.util.GregorianCalendar[time=1637023491089,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Asia/Shanghai",offset=28800000,dstSavings=0,useDaylight=false,transitions=31,lastRule=null],firstDayOfWeek=2,minimalDaysInFirstWeek=4,ERA=1,YEAR=2021,MONTH=10,WEEK_OF_YEAR=46,WEEK_OF_MONTH=3,DAY_OF_MONTH=16,DAY_OF_YEAR=320,DAY_OF_WEEK=3,DAY_OF_WEEK_IN_MONTH=3,AM_PM=0,HOUR=8,HOUR_OF_DAY=8,MINUTE=44,SECOND=51,MILLISECOND=89,ZONE_OFFSET=28800000,DST_OFFSET=0]

How do I checks if two dates are on the same day?

In this example, you will learn how to find out if two defined date objects are on the same day. It means that we are only interested in the date information and ignoring the time information of these date objects. We will be using an API provided by the Apache Commons Lang library. So here is the code snippet:

package org.kodejava.commons.lang;

import org.apache.commons.lang3.time.DateUtils;

import java.util.Calendar;
import java.util.Date;

public class CheckSameDay {
    public static void main(String[] args) {
        Date date1 = new Date();
        Date date2 = new Date();

        // Checks to see if the dates is on the same day.
        if (DateUtils.isSameDay(date1, date2)) {
            System.out.printf("%1$te/%1$tm/%1$tY and %2$te/%2$tm/%2$tY " +
                    "is on the same day.%n", date1, date2);
        }

        Calendar cal1 = Calendar.getInstance();
        Calendar cal2 = Calendar.getInstance();

        // Checks to see if the calendars is on the same day.
        if (DateUtils.isSameDay(cal1, cal2)) {
            System.out.printf("%1$te/%1$tm/%1$tY and %2$te/%2$tm/%2$tY " +
                    "is on the same day.%n", cal1, cal2);
        }

        cal2.add(Calendar.DAY_OF_MONTH, 10);
        if (!DateUtils.isSameDay(cal1, cal2)) {
            System.out.printf("%1$te/%1$tm/%1$tY and %2$te/%2$tm/%2$tY " +
                    "is not on the same day.", cal1, cal2);
        }
    }
}

The example results produced by this snippet are:

31/10/2021 and 31/10/2021 is on the same day.
31/10/2021 and 31/10/2021 is on the same day.
31/10/2021 and 10/11/2021 is not on the same day.

Maven Dependencies

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.13.0</version>
</dependency>

Maven Central