Home > Back-end >  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 like Apr 22 in java android?

Time:06-03

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.

CodePudding user response:

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));

CodePudding user response:

You can use SimpleDateFormat & Calendar to get desired result like below:

private void getFirstAndLastDate() {
    String input = "Apr 22";

    // Create two date format
    //One to read the date from the input string, the other to string the date
    SimpleDateFormat formats = new SimpleDateFormat("MMM yy", Locale.US);
    SimpleDateFormat newFormat = new SimpleDateFormat("ddMMyyyy", Locale.US);
    
    String firstDate, lastDate;

    try {
        Date date = formats.parse(input);
        Calendar myCalendar = Calendar.getInstance();
        myCalendar.setTime(date);

        // Just set the day to 1
        myCalendar.set(Calendar.DAY_OF_MONTH, 1);
        firstDate = newFormat.format(myCalendar.getTime());

        // Add a month
        // add day -1
        myCalendar.add(Calendar.MONTH, 1);
        myCalendar.add(Calendar.DAY_OF_MONTH, -1);
        lastDate = newFormat.format(myCalendar.getTime());

        Log.e("firstDate: ", firstDate);
        Log.e("lastDate: ", lastDate);

    } catch (ParseException e) {
        e.printStackTrace();
    }
}

It may not be the best way, but thus wanted results can be obtained.

  • Related