[英]How to get list of passed months of this year java?
I am using SingleLine chart from PhilJay/MPAndroidChart android library and i need a list of passed months of current year.我正在使用 PhilJay/MPAndroidChart android 库中的 SingleLine 图表,我需要一份当年过去月份的列表。 So for example from Jan to Oct, but when is October pass then from Jan to Nov and so on.
所以例如从一月到十月,但是十月什么时候过去,然后从一月到十一月等等。 I tried these: Getting List of Month for Past 1 year in Android dynamically , and Calculate previous 12 months from given month - SimpleDateFormat but all of these are for previosly 12 months and i want from start of current year
我尝试了这些: 在 Android 中动态获取过去 1 年的月份列表,并计算给定月份的前 12 个月 - SimpleDateFormat但所有这些都是以前的 12 个月,我想要从今年开始
@SuppressLint("SimpleDateFormat")
private void handleXAxis() {
List<String> allDates = new ArrayList<>();
String maxDate = "Jan";
SimpleDateFormat monthDate = new SimpleDateFormat("MMM");
Calendar cal = Calendar.getInstance();
try {
cal.setTime(Objects.requireNonNull(monthDate.parse(maxDate)));
} catch (ParseException e) {
e.printStackTrace();
}
for (int i = 1; i <= 12; i++) {
String month_name1 = monthDate.format(cal.getTime());
allDates.add(month_name1);
cal.add(Calendar.MONTH, -1);
}
}
java.time
java.time
Months until (including) the current one as List<YearMonth>
:直到(包括)当前月份的月份为
List<YearMonth>
:
public static List<YearMonth> getMonthsOfCurrentYear() {
YearMonth currentMonth = YearMonth.now();
List<YearMonth> yearMonths = new ArrayList<>();
for (int month = 1; month <= currentMonth.getMonthValue(); month++) {
yearMonths.add(YearMonth.of(currentMonth.getYear(), month));
}
return yearMonths;
}
Months until (including) the current one as List<String>
:几个月前(包括)当前的
List<String>
:
public static List<String> getMonthNamesOfCurrentYear() {
YearMonth currentMonth = YearMonth.now();
List<String> yearMonths = new ArrayList<>();
for (int month = 1; month <= currentMonth.getMonthValue(); month++) {
yearMonths.add(YearMonth.of(currentMonth.getYear(), month)
.format(DateTimeFormatter.ofPattern("MMM",
Locale.ENGLISH)));
}
return yearMonths;
}
as an alternative, you can use the display name of the Month
instead of using a DateTimeFormatter.ofPattern("MMM")
作为替代方案,您可以使用
Month
的显示名称而不是使用DateTimeFormatter.ofPattern("MMM")
public static List<String> getMonthNamesOfCurrentYear() {
YearMonth currentMonth = YearMonth.now();
List<String> yearMonths = new ArrayList<>();
for (int month = 1; month <= currentMonth.getMonthValue(); month++) {
yearMonths.add(Month.of(month)
.getDisplayName(TextStyle.SHORT, Locale.ENGLISH));
}
return yearMonths;
}
The output of the second and third example:第二个和第三个例子的输出:
Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct
when invoked like当被调用时
System.out.println(String.join(", ", getMonthNamesOfCurrentYear()));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.