How to get start and end date of a year?

前端 未结 15 1803
清酒与你
清酒与你 2021-02-05 02:57

I have to use the Java Date class for this problem (it interfaces with something out of my control).

How do I get the start and end date of a year and then

15条回答
  •  终归单人心
    2021-02-05 03:08

    java.time.YearMonth

    How to Get First Date and Last Date For Specific Year and Month.

    Here is code using YearMonth Class.

    YearMonth is a final class in java.time package, introduced in Java 8.

    public static void main(String[] args) {
    
        int year = 2021;  // you can pass any value of year Like 2020,2021...
        int month = 6;   // you can pass any value of month Like 1,2,3...
        YearMonth yearMonth = YearMonth.of( year, month );  
        LocalDate firstOfMonth = yearMonth.atDay( 1 );
        LocalDate lastOfMonth = yearMonth.atEndOfMonth();
    
        System.out.println(firstOfMonth);
        System.out.println(lastOfMonth);
    }
    

    See this code run live at IdeOne.com.

    2021-06-01

    2021-06-30

提交回复
热议问题