[转]java中如何利用时间间隔算日期

今天公司要要我实现一个功能是时间段1 时间段2 时间段3 时间段4这4个时间段的设备缺陷率盒和缺陷数量显示在dhtmlx grid的一个吧表格中,说来惭愧居然不知道如何利用时间间隔计算问题.在网上找了许久终于找出了一个办法现在记录下来.时间段1是现在的日期,2,3,4分别在前一时间段上面减去3个周.当然这里面也包含了Calendar Date 和字符串之间的相互转换
String a[] = time.split("年");
				String year = a[0];
				String b = a[1];
				String c[] = b.split("月");
				String month = c[0];
				String d = c[1];
				String day = d.substring(0,d.indexOf("日"));
				//时间段1
				if(Integer.parseInt(month) > 10 && Integer.parseInt(day) > 10){
					firstTime = year + "-" + month + "-" + day;
				}else if(Integer.parseInt(month) > 10 && Integer.parseInt(day) < 10){
					firstTime = year + "-" + month + "-0" + day;
				}else if(Integer.parseInt(month) < 10 && Integer.parseInt(day) > 10 ){
					firstTime = year + "-0" + month + "-" + day;
				}else if(Integer.parseInt(month) < 10 && Integer.parseInt(day) < 10){
					firstTime = year + "-0" + month + "-0" + day;
				}
				//时间段2
				try {
					Date date = df.parse(firstTime);
					Calendar c2 = Calendar.getInstance();
					c2.setTime(date);
					int d2 = c2.get(Calendar.DAY_OF_MONTH);
					d2 = d2 - 21;
					c2.set(Calendar.DAY_OF_MONTH, d2);
					secondTime = Constants.CharsetDecodeToUTF8(df.format(c2.getTime()));
				} catch (ParseException e) {
					e.printStackTrace();
				}
				
				
				//时间段3
				try {
					Date date = df.parse(secondTime);
					Calendar c3 = Calendar.getInstance();
					c3.setTime(date);
					int d3 = c3.get(Calendar.DAY_OF_MONTH);
					d3 = d3 - 21;
					c3.set(Calendar.DAY_OF_MONTH, d3);
					thirdTime = Constants.CharsetDecodeToUTF8(df.format(c3.getTime()));
				} catch (ParseException e) {
					e.printStackTrace();
				}
				
				
				//时间段4
				try {
					Date date = df.parse(secondTime);
					Calendar c4 = Calendar.getInstance();
					c4.setTime(date);
					int d4 = c4.get(Calendar.DAY_OF_MONTH);
					d4 = d4 - 21;
					c4.set(Calendar.DAY_OF_MONTH, d4);
					fourthTime = Constants.CharsetDecodeToUTF8(df.format(c4.getTime()));
				} catch (ParseException e) {
					e.printStackTrace();
				}
				




你可能感兴趣的:(java,calendar,日期处理)