Spring JPA Query to Check if the Current Date is Between a Range of Two Dates

  • Last updated Apr 25, 2024

Sometimes, there might be situations where you may require querying the database to determine whether the current date lies within a specified range of two dates. This can be useful, when dealing with time-sensitive data or when you need to retrieve records that are valid for a certain period.

To accomplish this task, you can create a custom query as shown in this example:

import java.util.Date;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import com.example.price.entity.Event;

@Repository
public interface EventRepository extends CrudRepository<Event, Long> {

  @Query("SELECT COUNT(e) > 0 FROM Event e WHERE :currentDate BETWEEN e.startDate AND e.endDate")
  boolean existsEventForCurrentDate(@Param("currentDate") Date currentDate);
}

Here's the entity class representing the data:

import java.util.Date;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;


@Entity
@Table(name = "event")
public class Event {

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;

  @Column(name = "start_date")
  private Date startDate;

  @Column(name = "end_date")
  private Date endDate;

  // getter and setter methods
}