最近用到了时间的查询,有一阵子没用时间在数据库和java上操作了。就发两个例子时间上的加减记录下。(问题最后还是靠数据库上的date_format('字符串时间','%Y-%m-%d %T')这样解决java传到数据库的String类型时间)
两个时间相差的月份(支持字符串的时间)
- public long getDistinceMonth(String beforedate, String afterdate) throws ParseException {
- SimpleDateFormat d = new SimpleDateFormat("yyyy-MM-dd");
- long monthCount=0;
- try{
- java.util.Date d1 = d.parse(beforedate);
- java.util.Date d2 = d.parse(afterdate);
- monthCount = (d2.getYear() - d1.getYear()) * 12 + d2.getMonth() - d1.getMonth();
- }catch(ParseException e){
- System.out.println("Date parse error!");
- }
- return monthCount;
- }
两个时间相差多少天
- public long getDistinceDay(String beforedate, String afterdate) throws ParseException {
- SimpleDateFormat d = new SimpleDateFormat("yyyy-MM-dd");
- long dayCount=0;
- try{
- java.util.Date d1 = d.parse(beforedate);
- java.util.Date d2 = d.parse(afterdate);
- dayCount = (d2.getTime()-d1.getTime())/(24*60*60*1000);
- }catch(ParseException e){
- System.out.println("Date parse error!");
- }
- return dayCount;
- }
有不正确的地方希望大家指点指点,共同学习。
转载于:https://blog.51cto.com/davenzeng/1054858