编程语言
首页 > 编程语言> > java 比较时间,DateDiff

java 比较时间,DateDiff

作者:互联网

之前是自己用 Calendar 类写,比较繁琐,也容易出错。在别人(项目经理)的推荐下,了解了一个专门的工具类

DateDiff

实现方式也是通过 Calendar 的方式

import java.util.Calendar;
import java.util.Date;

public class DateDiff {
    /**
       * 按指定日期单位计算两个日期间的间隔
       *
       * @param timeInterval,
       * @param date1,
       * @param date2
       * @return date1-date2,
       */
    public static synchronized long dateDiff(String timeInterval, Date date1, Date date2) {
if (timeInterval.equals("year")) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date1); int time = calendar.get(Calendar.YEAR); calendar.setTime(date2); return time - calendar.get(Calendar.YEAR); } if (timeInterval.equals("quarter")) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date1); int time = calendar.get(Calendar.YEAR) * 4; calendar.setTime(date2); time -= calendar.get(Calendar.YEAR) * 4; calendar.setTime(date1); time += calendar.get(Calendar.MONTH) / 4; calendar.setTime(date2); return time - calendar.get(Calendar.MONTH) / 4; } if (timeInterval.equals("month")) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date1); int time = calendar.get(Calendar.YEAR) * 12; calendar.setTime(date2); time -= calendar.get(Calendar.YEAR) * 12; calendar.setTime(date1); time += calendar.get(Calendar.MONTH); calendar.setTime(date2); return time - calendar.get(Calendar.MONTH); } if (timeInterval.equals("week")) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date1); int time = calendar.get(Calendar.YEAR) * 52; calendar.setTime(date2); time -= calendar.get(Calendar.YEAR) * 52; calendar.setTime(date1); time += calendar.get(Calendar.WEEK_OF_YEAR); calendar.setTime(date2); return time - calendar.get(Calendar.WEEK_OF_YEAR); } if (timeInterval.equals("day")) { long time = date1.getTime() / 1000 / 60 / 60 / 24; return time - date2.getTime() / 1000 / 60 / 60 / 24; } if (timeInterval.equals("hour")) { long time = date1.getTime() / 1000 / 60 / 60; return time - date2.getTime() / 1000 / 60 / 60; } if (timeInterval.equals("minute")) { long time = date1.getTime() / 1000 / 60; return time - date2.getTime() / 1000 / 60; } if (timeInterval.equals("second")) { long time = date1.getTime() / 1000; return time - date2.getTime() / 1000; } return date1.getTime() - date2.getTime(); } }

 

标签:date1,date2,java,get,DateDiff,time,calendar,比较,Calendar
来源: https://www.cnblogs.com/Kevin-QAQ/p/12917465.html