Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use reusable function – Android, Java

I implemented small if-else part to get First three letters of the month when Calendar instance = Calendar.getInstance(); retrieves integer value of the month. I wanna use it as a reusable function. I’ve tried by creating another java file but it want works. Can anyone tell me how can I use it?

public class MstrMonth {

    public MstrMonth() {}

    public static String getCurrentMonth(String currentMonth) {

        Calendar instance = Calendar.getInstance();
        int mMonth = instance.get(Calendar.MONTH) + 1;

        if(mMonth == 1){
            currentMonth = "JAN";
        }else if (mMonth == 2){
            currentMonth = "FEB";
        }else if (mMonth == 3){
            currentMonth = "MAR";
        }else if (mMonth == 4){
            currentMonth = "APR";
        }else if (mMonth == 5){
            currentMonth = "MAY";
        }else if (mMonth == 6){
            currentMonth = "JUN";
        }else if (mMonth == 7){
            currentMonth = "JUL";
        }else if (mMonth == 8){
            currentMonth = "AUG";
        }else if (mMonth == 9){
            currentMonth = "SEP";
        }else if (mMonth == 10){
            currentMonth = "OCT";
        }else if (mMonth == 11){
            currentMonth = "NOV";
        }else if (mMonth == 12){
            currentMonth = "DEC";
        }
        return currentMonth;
    }
}

In Main activity;

String currentMonth;
MstrMonth.getCurrentMonth(currentMonth);

I want get Month code in here but it gives null value.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Try this.

public static String getCurrentMonth() {
    Calendar instance = Calendar.getInstance();
    return instance.getDisplayName(
        Calendar.MONTH, Calendar.SHORT, Locale.ENGLISH).toUpperCase();
}

public static void main(String[] args) throws Exception {
    String currentMonth = getCurrentMonth();
    System.out.println(currentMonth);
}

output:

NOV
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading