Search code examples
javalocaldate

How to get date with year change in java


My method has following fields - id, year and month.

Collection<User> userCollection = getUserForMonth(int id, int year, int month);

User give me range of date. Between fromTimestamp and toTimestamp. I have to use method getUserForMonth so but I have no idea how to change these parameters (year and month) dynamiclly.

From timestamp I make start and end dat like that

LocalDate startDate = new Timestamp(csvRaportTransport.getFromTimestamp()).toLocalDateTime().toLocalDate();
LocalDate endDate = new Timestamp(csvRaportTransport.getToTimestamp()).toLocalDateTime().toLocalDate();

I can set up year and month like getStartDate but I do not know how to switch it.

I though about for but how change months and years? Have no idea. Could you please help me?


Solution

  • If you want to get all the users for all months between startDate and StartYear you can do like:

        LocalDate startDate = LocalDate.of(2018, 01, 1);
        LocalDate endDate = LocalDate.of(2018, 03, 1);
        while(startDate.isBefore(endDate))
        {
            getUserForMonth(123,startDate.getYear(), startDate.getMonthValue());
            startDate = startDate.plusMonths(1);//.plusYears if you want years
        }
    

    If you want to get the user for specific month in relations to startDate and endDate you can use:

        LocalDate startDate = LocalDate.of(2018, 01, 1);
        LocalDate endDate = LocalDate.of(2018, 03, 1);
    
        getUserForMonth(123,startDate.getYear(), startDate.getMonthValue());
        getUserForMonth(123,endDate.getYear(), endDate.getMonthValue());
    

    I hope it helps. As mentioned by user xxxvodnikxxx, you can read more about this in LocalDate javadoc provided in his comment