计算给定月份的前12个月-SimpleDateFormat [英] Calculate previous 12 months from given month - SimpleDateFormat
问题描述
我正在尝试将给定月份(从数据库中获取)的前12个月放入阵列列表中.
I am trying to get previous 12 month into an arraylist, from the given month(taken from DB).
List<String> allDates = new ArrayList<String>();
sqlQuery="select max(date) from Table_Name";
maxDate="Jan-2016"; (Result from Query);
要从maxDate获取之前的12个月,我在这里使用了SimpleDateFormat.
To get previous 12 months from maxDate,where i use SimpleDateFormat.
我想从 Given Month (maxDate)(maxDate)(而不是从当前月份)计算前12个月,我尝试了以下代码.
I want to calculate the previous 12 months from Given Month (maxDate), not from current month, i tried the following code.
// Parsing maxDate to an integer (say Jan-2016 = 0, Feb-2016= 1)
Date date = new SimpleDateFormat("MMM-yyyy").parse(maxDate);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int month=cal.get(Calendar.MONTH);
System.out.println("month : "+month);
// Looping to get previous 12 months from current month.
SimpleDateFormat month_date = new SimpleDateFormat("MMM-yyyy");
for (int i = 12; i > 0; i--) {
Calendar calendar1 = Calendar.getInstance();
calendar1.add(Calendar.MONTH, -i);
String month_name1 = month_date.format(calendar1.getTime());
allDates.add(month_name1);
}
System.out.println(allDates);
由于月份是从(0-11)编号的,所以我无法实现.请提出一个想法,计算给定月份的前12个月.感谢您的帮助!
Since months are numbered from (0 - 11) i couldn't achieve it. Please suggest an idea to calculate previous 12 months from given month. Appreciate your help!
推荐答案
问题是,在循环中,您总是根据当前日期而不是根据 maxDate
进行计算.
The problem is that in the loop you base the computation always from current date not from maxDate
.
List<String> allDates = new ArrayList<>();
String maxDate = "Jan-2016";
SimpleDateFormat monthDate = new SimpleDateFormat("MMM-yyyy");
Calendar cal = Calendar.getInstance();
cal.setTime(monthDate.parse(maxDate));
for (int i = 1; i <= 12; i++) {
String month_name1 = monthDate.format(cal.getTime());
allDates.add(month_name1);
cal.add(Calendar.MONTH, -1);
}
System.out.println(allDates);
输出
[Jan-2016, Dec-2015, Nov-2015, Oct-2015, Sep-2015, Aug-2015, Jul-2015, Jun-2015, \
May-2015, Apr-2015, Mar-2015, Feb-2015]
编辑简短说明代码段的作用.
edit Short explanation what the snippet does.
- 从给定的
maxDate
创建一个Calendar
,并将其分配给cal
- 将
cal
中当前日期的字符串Mon-Year
添加到列表allDates
- 从日历中减去一个月
cal.add(Calendar.MONTH,-1)
- 将步骤2和3.重复十二次
- create a
Calendar
from the givenmaxDate
and assign it tocal
- add the string
Mon-Year
of the current date incal
to the listallDates
- substract one month from the calendar
cal.add(Calendar.MONTH, -1)
- repeat steps 2. and 3. twelve times
如罗勒所述.如果以后要以 Date/Calendar
处理 allDates
中的值,请考虑不要在两者之间生成字符串列表.
As mentioned by Basil. If you want to process the values in allDates
later on as Date / Calendar
think about not to generate a list of strings in between.
这篇关于计算给定月份的前12个月-SimpleDateFormat的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!