Java Tutorial

Operators

Flow Control

String

Number and Date

Built-in Classes

Array

Class and Object

Inheritance and Polymorphism

Exception Handling

Collections, Generics and Enumerations

Reflection

Input/Output Stream

Annotation

Java Date Query

When working with dates in Java, you may need to query and manipulate dates for various purposes, such as finding the day of the week or adding days to a date. In Java 8 and later versions, the recommended way to work with dates is to use the java.time package, which includes classes such as LocalDate, LocalTime, and LocalDateTime.

In this tutorial, we'll cover some common date queries using the java.time.LocalDate class.

  • Getting the current date

To get the current date, use the LocalDate.now() method.

Example:

import java.time.LocalDate;

public class Main {
    public static void main(String[] args) {
        LocalDate currentDate = LocalDate.now();
        System.out.println("Current date: " + currentDate);
    }
}
  • Creating a specific date

To create a specific date, use the LocalDate.of() method.

Example:

import java.time.LocalDate;

public class Main {
    public static void main(String[] args) {
        LocalDate specificDate = LocalDate.of(2022, 5, 4);
        System.out.println("Specific date: " + specificDate);
    }
}
  • Getting the day of the week

To get the day of the week for a given date, use the getDayOfWeek() method.

Example:

import java.time.LocalDate;
import java.time.DayOfWeek;

public class Main {
    public static void main(String[] args) {
        LocalDate date = LocalDate.of(2022, 5, 4);
        DayOfWeek dayOfWeek = date.getDayOfWeek();
        System.out.println("Day of the week: " + dayOfWeek);
    }
}
  • Adding or subtracting days, months, or years

To add or subtract days, months, or years from a date, use the plusDays(), plusMonths(), plusYears(), minusDays(), minusMonths(), or minusYears() methods.

Example:

import java.time.LocalDate;

public class Main {
    public static void main(String[] args) {
        LocalDate date = LocalDate.of(2022, 5, 4);
        LocalDate plusDays = date.plusDays(7);
        LocalDate minusMonths = date.minusMonths(1);
        LocalDate plusYears = date.plusYears(5);

        System.out.println("Original date: " + date);
        System.out.println("Plus 7 days: " + plusDays);
        System.out.println("Minus 1 month: " + minusMonths);
        System.out.println("Plus 5 years: " + plusYears);
    }
}
  • Comparing dates

To compare dates, use the isBefore(), isAfter(), or isEqual() methods.

Example:

import java.time.LocalDate;

public class Main {
    public static void main(String[] args) {
        LocalDate date1 = LocalDate.of(2022, 5, 4);
        LocalDate date2 = LocalDate.of(2022, 6, 1);

        boolean isBefore = date1.isBefore(date2);
        boolean isAfter = date1.isAfter(date2);
        boolean isEqual = date1.isEqual(date2);

        System.out.println("Date1 is before Date2: " + isBefore);
        System.out.println("Date1 is after Date2: " + isAfter);
        System.out.println("Date1 is equal to Date2: " + isEqual);
    }
}

In summary, the java.time.LocalDate class provides various methods to query and manipulate dates in Java.

  1. Comparing dates in Java using Date class

    The Date class in Java provides methods for comparing dates. Example:

    Date date1 = new Date();
    Date date2 = new Date();
    
    if (date1.compareTo(date2) == 0) {
        System.out.println("Dates are equal");
    } else if (date1.after(date2)) {
        System.out.println("date1 is after date2");
    } else {
        System.out.println("date1 is before date2");
    }
    
  2. Date manipulation and querying in Java

    Manipulating and querying dates involve tasks such as adding or subtracting time, extracting components, and checking for specific conditions.

    Calendar calendar = Calendar.getInstance();
    calendar.add(Calendar.DAY_OF_MONTH, 7); // Add 7 days
    Date futureDate = calendar.getTime();
    
    if (futureDate.after(new Date())) {
        System.out.println("Future date!");
    }
    
  3. Searching for dates in a collection in Java

    Searching for dates in a collection can be done using iteration or stream operations.

    List<Date> dateList = new ArrayList<>();
    // Populate dateList
    
    Date searchDate = // specify the date to search
    
    if (dateList.contains(searchDate)) {
        System.out.println("Date found in the collection");
    }
    
  4. Date range queries in Java

    Date range queries involve filtering dates within a specified range.

    List<Date> dateList = new ArrayList<>();
    // Populate dateList
    
    Date startDate = // specify start date
    Date endDate = // specify end date
    
    List<Date> datesInRange = dateList.stream()
                            .filter(date -> date.after(startDate) && date.before(endDate))
                            .collect(Collectors.toList());
    
  5. Using LocalDate and LocalDateTime for date queries

    The LocalDate and LocalDateTime classes in the java.time package provide enhanced functionality for date queries.

    LocalDate currentDate = LocalDate.now();
    
    if (currentDate.isLeapYear()) {
        System.out.println("Current year is a leap year");
    }
    
  6. Sorting dates in Java for efficient querying

    Sorting dates enables efficient querying, especially when dealing with large datasets.

    List<Date> dateList = new ArrayList<>();
    // Populate dateList
    
    Collections.sort(dateList);
    
    // Now dateList is sorted in ascending order
    
  7. Querying database records based on dates in Java

    When querying a database based on dates, you can use SQL queries or an ORM framework like Hibernate.

    // Using JDBC
    PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM myTable WHERE dateColumn > ?");
    preparedStatement.setDate(1, new java.sql.Date(searchDate.getTime()));
    
    ResultSet resultSet = preparedStatement.executeQuery();