时间对比、流水号计算、100%统计

项目最近有个几以前没遇到的场景,记录下来,供以后查阅,有更好实现的盆友,忘多多分享。

时间对比

private static void diffTime() {
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		try {
			Date d1 = df.parse("2004-12-03");
			Date d2 = df.parse("2004-12-12");
			System.out.println(d2.before(d1));
		} catch (ParseException e) {
			//格式错误
		}
	}


通过Date方法的before和after方法判断


100%统计

private static double getAllFund(String govFund, String stateFund, String collectiveFund,
				String privateFund, String foreignFund, String otherFund) {
			double sum = add(govFund, stateFund);
			sum = add(Double.toString(sum), collectiveFund);
			sum = add(Double.toString(sum), privateFund);
			sum = add(Double.toString(sum), foreignFund);
			sum = add(Double.toString(sum), otherFund);
			return sum;
		}
	 
	 	public static double add(String v1, String v2) {
		  BigDecimal b1 = new BigDecimal(v1);
		  BigDecimal b2 = new BigDecimal(v2);
		  return b1.add(b2).doubleValue();
		 }


根据多个百分数统计,最后统计出总和,使用BigDecimal避免出现多为小数点的情况。


流水号计算

private static Calendar pre= null ;
	private static int index = 1;
	private static SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
	
	public static synchronized String getSerialNumber() {
		Calendar current = Calendar.getInstance();
		StringBuffer sb = new StringBuffer(sdf.format(current.getTime()));
		if (pre == null) {//刚进入
			pre = current;
			index = 1;
			sb.append("001");
		} else {//比较年月日,相同时加1
			int preYear=pre.get(Calendar.YEAR);//得到年
			int preMonth=pre.get(Calendar.MONTH)+1;//得到月,因为从0开始的,所以要加1
			int preDay=pre.get(Calendar.DAY_OF_MONTH);//得到天
			int currentYear=current.get(Calendar.YEAR);//得到年
			int currentMonth=current.get(Calendar.MONTH)+1;//得到月,因为从0开始的,所以要加1
			int currentDay=current.get(Calendar.DAY_OF_MONTH);//得到天
			if (preYear == currentYear && preMonth==currentMonth && preDay == currentDay) {//当年月日相同时,流水号加1
				String temp = String.valueOf(++index);
				int length = temp.length();
				for(int i = 0; i<3-length;i++) {
					sb.append("0");
				}
				sb.append(temp);
			} else {//不同时,从001开始
				pre = current;
				index = 1;
				sb.append("001");
			}
		}
		return sb.toString();
	}

流水号以年月日加上后3位数字,从001开始。


你可能感兴趣的:(Date,BigDecimal)