我正试图找到一种方法来获得一年array
个月(例如:2017
)
例如:{ “October
”, “November
”, “December
”}
到目前为止我做了什么:我能够获得当前年份
Date now = new Date();
int year = now.getYear();
答案 0 :(得分:2)
您应该更好地使用新的API LocalDate
而不是Date
,它更容易使用
date
: 此处07/10/201 array
size + 1
(当前月份为+1): 此处尺寸为3 array
填入您拥有的日期+ i
个月LocalDate date = LocalDate.now();
int nbMonthRemain = 12 - date.getMonth().getValue();
String[] monthsRemaining = new String[nbMonthRemain + 1];
for (int i = 0; i < monthsRemaining.length; i++) {
monthsRemaining[i] = date.plusMonths(i).getMonth().toString();
}
System.out.println(Arrays.toString(monthsRemaining)); // [OCTOBER, NOVEMBER, DECEMBER]
提示:
将.toString()
替换为:
.getDisplayName(TextStyle.FULL, Locale.ENGLISH);
获取[October, November, December]
.getDisplayName(TextStyle.FULL_STANDALONE, Locale.ENGLISH);
获取[10, 11, 12]
.getDisplayName(TextStyle.SHORT, Locale.ENGLISH);
获取[Oct, Nov, Dec]
答案 1 :(得分:0)
使用GregorianCalendar.getInstance().get(Calendar.MONTH)
获取当前月份数(对于oct,您将得到9)
答案 2 :(得分:0)
i believe something like below code could help
import java.text.DateFormatSymbols;
import java.util.List;
import java.util.ArrayList;
public List GetLeftMonth(Integer Mon_num){
List<String> monthsList = new ArrayList<String>();
String[] months = new DateFormatSymbols().getMonths();
for (int i = Mon_num; i < months.length; i++) {
String month = months[i];
System.out.println("month = " + month);
monthsList .add(months[i]);
}
return monthsList;
}
答案 3 :(得分:0)
public static void main(String[] args) {
LocalDate now = LocalDate.now();
int currentMonth = now.getMonthValue();
int monthsInAYear = 12;
int monthsRemaining = monthsInAYear - currentMonth;
System.out.println(monthsRemaining); // 2
for (int i = currentMonth; i <= monthsInAYear; i++) {
System.out.println(getMonthName(i)); // OCTOBER NOVEMBER DECEMBER
}
}
private static Month getMonthName(int monthValue) {
return Month.of(monthValue);
}
不要忘记导入import java.time.LocalDate;
import java.time.Month;
正如已经说过的那样,不要使用java.util.Date
而是使用java.time.LocalDate
,因为它(可以说)更容易使用。