Search code examples
javadayofweekdate

Get last and first day using Java


I have a requirement which is as follows: for example if today is Sunday then I need to get first Sunday and last Sunday in next month, and so on for all days in the week. I need to get the first and last day in next month.

Any idea on how I can do it

Is there a generic way to do it, or do I need to deal with each day separately? I have tried many ways, but all I found is each day has a special formula.

The technology I am using is Java.


Solution

  • You could try this

    public static void main(String... args) {
        LocalDate now = LocalDate.now();
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("EEE: dd-MM-yyyy");
    
        System.out.println("Now " + now.format(dtf));
        System.out.println("First " + getFirstDayOfNextMonth(now).format(dtf));
        System.out.println("Last " + getLastDayOfNextMonth(now).format(dtf));
    }
    
    public static LocalDate getLastDayOfNextMonth(LocalDate localDate) {
        return localDate
                .plusMonths(1)
                .with(TemporalAdjusters.lastInMonth(localDate.getDayOfWeek()));
    }
    
    
    public static LocalDate getFirstDayOfNextMonth(LocalDate localDate) {
        return localDate
                .plusMonths(1)
                .with(TemporalAdjusters.firstInMonth(localDate.getDayOfWeek()));
    }
    

    Output:

    Now Sun: 03-05-2020
    First Sun: 07-06-2020
    Last Sun: 28-06-2020