javaspring-bootformattinglocaldate

Is there a way to format a LocalDate to take just the month and year


I have a spring boot app that I want the admin to be able to get the system report based on the month and year selected. System report in this case is the number of sales that was made in the selected month. The SaleEntity class has one attribute called datePurchased which is of type LocalDate. I want to retrieve all the sales that was made based on the selected month and year. The frontend is passing something like this "July-2024". And from what I know about LocalDate, its format is like this "2024-07-17". I do not want to use Date because there are other operations that I want to do with the model class in which I thought that using LocalDate will make me to achieve that easily. If I use Date, I can just format it to take month and year and I will be good to go but like I said, I have other operations to perform of which I think that using LocalDate will make me to achieve that easily. This is what I tried.

@Repository
public interface SaleRepository extends JpaRepository<SaleEntity,Long> {

    List<SaleEntity> findByDatePurchased(LocalDate localDate);
}

   private List<SaleEntity> getSelectedMonthSale(LocalDate localDate){
        return saleRepository.findByDatePurchased(localDate);
    }

Solution

  • I think the better way to do that is using @Query

    @Query("SELECT s FROM SaleEntity s WHERE YEAR(s.datePurchased) = :year AND MONTH(s.datePurchased) = :month")
    List<SaleEntity> findSalesByMonthAndYear(@Param("year") int year, @Param("month") int month);