javadate

Convert month name to Date range


I need to convert Monthname + Year to a valid date range. It needs to work with leap years etc.

Examples

getDateRange("Feb",2015)  

should find the range 2015-02-01 -- 2015-02-28

While

getDateRange("Feb",2016)  

should find the range 2016-02-01 -- 2016-02-29


Solution

  • java.time.temporal.TemporalAdjusters

    In Java 8, you can do that using TemporalAdjusters,

    LocalDate firstDate= date.with(TemporalAdjusters.firstDayOfMonth());
    
    LocalDate lastDate= date.with(TemporalAdjusters.lastDayOfMonth());
    

    java.time.YearMonth

    If you have only year and month, it is better to use YearMonth. From YearMonth you can easily get length of that month.

     YearMonth ym= YearMonth.of(2015, Month.FEBRUARY);
     int monthLen= ym.lengthOfMonth();