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(); } }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM