我试图将前12个月变为一个arraylist,从给定月份(取自DB)。
List<String> allDates = new ArrayList<String>();
sqlQuery="select max(date) from Table_Name";
maxDate="Jan-2016"; (Result from Query);
从maxDate获取前12个月,我使用SimpleDateFormat。
我想从给定月(maxDate)计算前12个月,而不是从当前月份,我尝试以下代码。
// 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个月。感谢您的帮助!
问题是,在循环中,您始终从当前日期开始计算,而不是从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]
编辑简短说明代码片段的作用。
Calendar
创建一个maxDate
并将其分配给cal
Mon-Year
中添加当前日期的字符串cal
到列表allDates
如巴兹尔所述。如果你想稍后处理cal.add(Calendar.MONTH, -1)
中的值,因为allDates
考虑不生成中间的字符串列表。
将日期时间值表示为文本有一个合理的标准:Date / Calendar
。
因此,我强烈建议您使用标准格式ISO 8601,而不是将您的年月值序列化为Jan-2016
。即使在英语以外的语言中,此格式也可以直观地阅读。
您正在使用与最早版本的Java捆绑在一起的麻烦的旧日期时间类。正如您所了解的那样,他们糟糕的设计选择是零基础的月份数字0-11。
Sun和Oracle放弃了这些旧类,用Java 8及更高版本中内置的2016-01
框架取代它们。
这些课程正是您所需要的:YearMonth
。顾名思义,是一年和一个月的组合。
而不是处理字符串,而是传递此类型的对象。鉴于该类是内置于Java中,您可以在代码库中依赖此类。
要解析非标准字符串,请定义格式化程序。为人类语言指定YearMonth
,通过该语言翻译月份名称。
Locale
要解析标准字符串,不需要格式化程序。默认情况下,java.time类支持解析/生成ISO 8601字符串。
DateTimeFormatter formatter = formatter.ofPattern( "MMM-yyyy" );
formatter = formatter.withLocale( Locale.US ) ;
YearMonth stop = YearMonth.parse( "Jan-2016" , formatter );
YearMonth stop = YearMonth.parse( "2016-01" );
类提供了添加和减去时间的方法。
YearMonth
定义YearMonth start = stop.minusYears( 1 );
类型的集合。
YearMonth
循环,一次增加一个月,直到我们到达停止月份。您要求半开放式方法,其中时间跨度的开始是包容性的,而结束是独占的。这种半开放式方法在日期工作中很常见。
List<YearMonth> yearMonths = new ArrayList<>( 12 );
YearMonth yearMonth = start ;
while ( yearMonth.isBefore( stop ) ) {
yearMonths.add( yearMonth ) ; // Add each incremented YearMonth to our collection.
// Set up next loop.
yearMonth.addMonths( 1 );
}
SQL查询:
public static void main(String[] args) {
Calendar c = Calendar.getInstance();
c.setTime(new Date()); //Give Your Date
c.add(Calendar.MONTH, -12);
Date fromDate = c.getTime();
Date toDate = new Date(); //Give Your Date
System.out.println("from "+fromDate);
System.out.println(" to "+fromDate);
}