javaandroiddatemonthcalendar

How can I get start date and end date of a given month like Apr 22 in java android?


How can I get start date and end date of a given month. But here the month is coming in the format of 'Apr 22' . So I need to get the start date and end date of April 2022.

How can I get this in java? The format I am looking is ddMMyyyy.


Solution

  • You can use the YearMonth class from the java.time api to parse your input and get the first and last day of month as LocalDate:

    import java.time.LocalDate;
    import java.time.YearMonth;
    import java.time.format.DateTimeFormatter;
    
    ....
    
    String input = "Apr 22";
    DateTimeFormatter ymFormater = DateTimeFormatter.ofPattern("MMM uu");
    DateTimeFormatter dtFormater = DateTimeFormatter.ofPattern("ddMMuuuu");
    
    LocalDate startOfMonth = YearMonth.parse(input, ymFormater).atDay(1);
    LocalDate endOfMonth   = YearMonth.parse(input, ymFormater).atEndOfMonth();
    
    System.out.println(startOfMonth.format(dtFormater));
    System.out.println(endOfMonth.format(dtFormater));