0

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.

T B
  • 191
  • 4
  • 22

2 Answers2

3

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));
Eritrean
  • 15,851
  • 3
  • 22
  • 28
  • This solution require @RequiresApi(api = Build.VERSION_CODES.O) but I need to get support from api level 23 @Eritrean – T B Jun 03 '22 at 12:42
  • 1
    @TB I am not familliar with Android, but according to this post it looks like you can use Java8 features by using D8 Core Library Desugaring. [call-requires-api-level-26-current-min-is-23-java-time-instantnow](https://stackoverflow.com/questions/55550936/call-requires-api-level-26-current-min-is-23-java-time-instantnow) You may also want to read this post if you are using other Gradle plugins [java8-support](https://developer.android.com/studio/write/java8-support) – Eritrean Jun 03 '22 at 14:50
1

Solution 1:

As per your need to get support from API level 23 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.

Solution 2:

(Added as per advice of @Ole V.V, thanks for guidance)

The best way to get desired result, you should use @Eritrean's suggestion which I have adding as quoted below.

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

This solution require @RequiresApi(api = Build.VERSION_CODES.O) but I need to get support from api level 23

In that case please add the following code to "build.gradle (module)" in order to get support from API level 23.

android {

    ...

    compileOptions {
        // Flag to enable support for the new language APIs
        coreLibraryDesugaringEnabled true
        // Sets Java compatibility to Java 8
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

dependencies {

    ...

    coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:1.1.5'
}

You should check the links for more details (desugaring, Java 8+ API desugaring support).

Gouranga Das
  • 374
  • 3
  • 10
  • Please don’t teach the young ones to use the long outdated and notoriously troublesome `SimpleDateFormat` class. At least not as the first option. And not without any reservation. We have so much better in [`java.time`, the modern Java date and time API,](https://docs.oracle.com/javase/tutorial/datetime/) and its `DateTimeFormatter`. Yes, you can use it on Android. For older Android look into [desugaring](https://developer.android.com/studio/write/java8-support-table). – Ole V.V. Jun 03 '22 at 16:51
  • Hi @Ole V.V., as per need of @T B to get support from api level 23, I have posted it. ```DateTimeFormatter.ofPattern``` isn't available on api level 23. – Gouranga Das Jun 03 '22 at 17:12
  • On one hand sorry, I had not read that comment under the other answer requiring min level 23. On the other hand I did mention desugaring already. Indeed you can use `DateTimeFormatter.ofPattern` for level 23. And probably thousands of other readers will read your answer, hundreds of them also not being aware that this was written specifically for level 23 and thus risking being led astray. – Ole V.V. Jun 03 '22 at 19:33