如何使用可重复使用的功能-Android,Java



当Calendar instance=Calendar.getInstance((时,我实现了小的if-else部分来获取月份的前三个字母;检索月份的整数值。我想把它作为一个可重复使用的函数。我尝试过创建另一个java文件,但它不起作用。有人能告诉我怎么用吗?

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

在主要活动中;

String currentMonth;
MstrMonth.getCurrentMonth(currentMonth);

我想在这里得到Month代码,但它给出了null值。

试试这个。

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

输出:

NOV

试试这个代码,在我的测试项目中工作


public class MstrMonth {
public MstrMonth() {}
public static String getCurrentMonth() {
String currentMonth = null;
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;
}
}

活动中


String currentMonth = MstrMonth.getCurrentMonth(currentMonth);

最新更新