Java对日期Date类进行日期加减运算,年份加减,月份加减

简介: 1 package com.cy; 59 import java.security.InvalidParameterException; 60 import java.text.ParseException; 61 import java.
  1 package com.cy;

 59 import java.security.InvalidParameterException;
 60 import java.text.ParseException;
 61 import java.text.SimpleDateFormat;
 62 import java.util.ArrayList;
 63 import java.util.Calendar;
 64 import java.util.Date;
 65 import java.util.HashMap;
 66 import java.util.Map;
 67 
 68 public class DateUtils {
 69     private static final long MILLIS_IN_A_SECOND = 1000;
 70 
 71     private static final long SECONDS_IN_A_MINUTE = 60;
 72 
 73     private static final int MONTHS_IN_A_YEAR = 12;
 74 
 75     /**
 76      * 获得指定日期之后一段时期的日期。例如某日期之后3天的日期等 时间为23:59:59。
 77      * 
 78      * @param origDate
 79      *            基准日期
 80      * @param amount
 81      *            时间数量
 82      * @param timeUnit
 83      *            时间单位,如年、月、日等。用Calendar中的常量代表
 84      * @return {@link Date}
 85      */
 86     public static final Date dateAfter(Date origDate, int amount, int timeUnit) {
 87         Calendar calendar = Calendar.getInstance();
 88         calendar.setTime(origDate);
 89         // 将小时至0
 90         // calendar.set(Calendar.HOUR_OF_DAY, 23);
 91         // 将分钟至0
 92         // calendar.set(Calendar.MINUTE, 59);
 93         // 将秒至0
 94         // calendar.set(Calendar.SECOND, 59);
 95         // 将毫秒至0
 96         // calendar.set(Calendar.MILLISECOND, 0);
 97         calendar.add(timeUnit, amount);
 98         return calendar.getTime();
 99     }
100 
101     /**
102      * 获得指定日期之后一段时期的日期。例如某日期之后3天的日期等。
103      * 
104      * @param origDate
105      *            基准日期
106      * @param amount
107      *            时间数量
108      * @param timeUnit
109      *            时间单位,如年、月、日等。用Calendar中的常量代表
110      * @return {@link Date}
111      */
112     public static final Date timeAfter(Date origDate, int amount, int timeUnit) {
113         Calendar calendar = Calendar.getInstance();
114         calendar.setTime(origDate);
115         calendar.add(timeUnit, amount);
116         return calendar.getTime();
117     }
118 
119     /**
120      * 获得指定日期之前一段时期的日期。例如某日期之前3天的日期等。
121      * 
122      * @param origDate
123      *            基准日期
124      * @param amount
125      *            时间数量
126      * @param timeUnit
127      *            时间单位,如年、月、日等。用Calendar中的常量代表
128      * @return {@link Date}
129      */
130     public static final Date dateBefore(Date origDate, int amount, int timeUnit) {
131         Calendar calendar = Calendar.getInstance();
132         calendar.add(timeUnit, -amount);
133         return calendar.getTime();
134     }
135 
136     /**
137      * 根据年月日构建日期对象。注意月份是从1开始计数的,即month为1代表1月份。
138      * 
139      * @param year
140      *            年
141      * @param month
142      *            月。注意1代表1月份,依此类推。
143      * @param day
144      *            日
145      * @return {@link Date}
146      */
147     public static Date date(int year, int month, int date) {
148         Calendar calendar = Calendar.getInstance();
149         calendar.set(year, month - 1, date, 0, 0, 0);
150         calendar.set(Calendar.MILLISECOND, 0);
151         return calendar.getTime();
152     }
153 
154     /**
155      * 计算两个日期(不包括时间)之间相差的周年数
156      * 
157      * @param date1
158      *            开始时间
159      * @param date2
160      *            结束时间
161      * @return {@link Integer}
162      */
163     public static int getYearDiff(Date date1, Date date2) {
164         if (date1 == null || date2 == null) {
165             throw new InvalidParameterException("date1 and date2 cannot be null!");
166         }
167         if (date1.after(date2)) {
168             throw new InvalidParameterException("date1 cannot be after date2!");
169         }
170 
171         Calendar calendar = Calendar.getInstance();
172         calendar.setTime(date1);
173         int year1 = calendar.get(Calendar.YEAR);
174         int month1 = calendar.get(Calendar.MONTH);
175         int day1 = calendar.get(Calendar.DATE);
176 
177         calendar.setTime(date2);
178         int year2 = calendar.get(Calendar.YEAR);
179         int month2 = calendar.get(Calendar.MONTH);
180         int day2 = calendar.get(Calendar.DATE);
181 
182         int result = year2 - year1;
183         if (month2 < month1) {
184             result--;
185         } else if (month2 == month1 && day2 < day1) {
186             result--;
187         }
188         return result;
189     }
190 
191     /**
192      * 计算两个日期(不包括时间)之间相差的整月数
193      * 
194      * @param date1
195      *            开始时间
196      * @param date2
197      *            结束时间
198      * @return {@link Integer}
199      */
200     public static int getMonthDiff(Date date1, Date date2) {
201         if (date1 == null || date2 == null) {
202             throw new InvalidParameterException("date1 and date2 cannot be null!");
203         }
204         if (date1.after(date2)) {
205             throw new InvalidParameterException("date1 cannot be after date2!");
206         }
207 
208         Calendar calendar = Calendar.getInstance();
209         calendar.setTime(date1);
210         int year1 = calendar.get(Calendar.YEAR);
211         int month1 = calendar.get(Calendar.MONTH);
212         int day1 = calendar.get(Calendar.DATE);
213 
214         calendar.setTime(date2);
215         int year2 = calendar.get(Calendar.YEAR);
216         int month2 = calendar.get(Calendar.MONTH);
217         int day2 = calendar.get(Calendar.DATE);
218 
219         int months = 0;
220         if (day2 >= day1) {
221             months = month2 - month1;
222         } else {
223             months = month2 - month1 - 1;
224         }
225         return (year2 - year1) * MONTHS_IN_A_YEAR + months;
226     }
227 
228     /**
229      * 统计两个日期之间包含的天数。包含date1,但不包含date2
230      * 
231      * @param date1
232      *            开始时间
233      * @param date2
234      *            结束时间
235      * @return {@link Integer}
236      * @throws ParseException
237      */
238     public static int getDayDiff(Date date1, Date date2) {
239         if (date1 == null || date2 == null) {
240             throw new InvalidParameterException("date1 and date2 cannot be null!");
241         }
242         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
243         Date smdate;
244         try {
245             smdate = sdf.parse(sdf.format(date1));
246             Date bdate = sdf.parse(sdf.format(date2));
247             Calendar cal = Calendar.getInstance();
248             cal.setTime(smdate);
249             long time1 = cal.getTimeInMillis();
250             cal.setTime(bdate);
251             long time2 = cal.getTimeInMillis();
252             long between_days = (time2 - time1) / (1000 * 3600 * 24);
253             return Integer.parseInt(String.valueOf(between_days));
254         } catch (ParseException e) {
255             e.printStackTrace();
256         }
257         return 0;
258     }
259 
260     /**
261      * 计算time2比time1晚多少分钟,忽略日期部分
262      * 
263      * @param time1
264      * @param time2
265      * @return
266      */
267     public static int getMinuteDiffByTime(Date time1, Date time2) {
268         long startMil = 0;
269         long endMil = 0;
270         Calendar calendar = Calendar.getInstance();
271         calendar.setTime(time1);
272         calendar.set(1900, 1, 1);
273         startMil = calendar.getTimeInMillis();
274         calendar.setTime(time2);
275         calendar.set(1900, 1, 1);
276         endMil = calendar.getTimeInMillis();
277         return (int) ((endMil - startMil) / MILLIS_IN_A_SECOND / SECONDS_IN_A_MINUTE);
278     }
279 
280     /**
281      * 计算时间是否是同一天
282      * 
283      * @param dateA
284      * @param dateB
285      * @return
286      */
287     public static boolean areSameDay(Date dateA, Date dateB) {
288         Calendar calDateA = Calendar.getInstance();
289         calDateA.setTime(dateA);
290 
291         Calendar calDateB = Calendar.getInstance();
292         calDateB.setTime(dateB);
293 
294         return calDateA.get(Calendar.YEAR) == calDateB.get(Calendar.YEAR)
295                 && calDateA.get(Calendar.MONTH) == calDateB.get(Calendar.MONTH)
296                 && calDateA.get(Calendar.DAY_OF_MONTH) == calDateB.get(Calendar.DAY_OF_MONTH);
297     }
298 
299     /**
300      * @Title: getCurrYearLast
301      * @Description: 获取某年最后一天
302      * @param date
303      * @return Date
304      */
305     public static Date getCurrYearLast(Date date) {
306         Calendar currCal = Calendar.getInstance();
307         currCal.setTime(date);
308         int currentYear = currCal.get(Calendar.YEAR);
309         return getYearLast(currentYear);
310     }
311 
312     private static Date getYearLast(int year) {
313         Calendar calendar = Calendar.getInstance();
314         calendar.clear();
315         calendar.set(Calendar.YEAR, year);
316 
317         calendar.roll(Calendar.DAY_OF_YEAR, -1);
318         // 将小时至0
319         calendar.set(Calendar.HOUR_OF_DAY, 23);
320         // 将分钟至0
321         calendar.set(Calendar.MINUTE, 59);
322         // 将秒至0
323         calendar.set(Calendar.SECOND, 59);
324         // 将毫秒至0
325         calendar.set(Calendar.MILLISECOND, 0);
326 
327         Date currYearLast = calendar.getTime();
328         return currYearLast;
329     }
330     /*
331      * private static Date getYearLast(int year) { Calendar calendar =
332      * Calendar.getInstance(); calendar.clear(); calendar.set(Calendar.YEAR,
333      * year); calendar.roll(Calendar.DAY_OF_YEAR, -1); Date currYearLast =
334      * calendar.getTime(); return currYearLast; }
335      */
336     /**
337      * 
338      * @param args
339      * @throws ParseException
340      * 
341      * 根据结算周期数  对开始时间与结束时间进行分段
342      */
343     public static void main(String[] args) throws ParseException {
344         /*开始时间*/
345         Date startDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2017-1-20 10:31:36");
346         /*结束时间*/
347         Date endDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2017-5-12 10:31:36");
348         /*周期数*/
349         int solt = 2;
350         ArrayList<Map<String, Object>> list = new ArrayList<>();
351         
352         while (startDate.getTime()<endDate.getTime()) {
353             Map<String, Object> map = new HashMap<>();
354             map.put("开始时间",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(startDate));
355             startDate=dateAfter(startDate, solt, Calendar.MONTH);
356             if (startDate.getTime()>endDate.getTime()) {
357                 map.put("结束时间",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(endDate));
358                 
359             } else {
360                 map.put("结束时间",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(startDate));
361             }
362             list.add(map);
363         }
364         System.out.println(list);
365     }
366 }

 

相关文章
|
2月前
|
Java 开发者
在 Java 中,一个类可以实现多个接口吗?
这是 Java 面向对象编程的一个重要特性,它提供了极大的灵活性和扩展性。
166 57
|
11天前
|
Java API 调度
Java 日期与时间处理:精准掌控时间流转
Java 8引入了全新的日期和时间API,解决了旧版`java.util.Date`和`Calendar`类设计不佳、操作繁琐的问题。新API包括`LocalDate`、`LocalTime`和`LocalDateTime`类,操作简洁直观,符合日常思维习惯。同时提供了`Period`和`Duration`处理时间间隔,以及`DateTimeFormatter`进行格式化输出。这些改进使开发者能更高效、准确地处理日期和时间,极大提升了开发效率与代码质量。 (239字符)
41 5
|
22天前
|
JSON Java Apache
Java基础-常用API-Object类
继承是面向对象编程的重要特性,允许从已有类派生新类。Java采用单继承机制,默认所有类继承自Object类。Object类提供了多个常用方法,如`clone()`用于复制对象,`equals()`判断对象是否相等,`hashCode()`计算哈希码,`toString()`返回对象的字符串表示,`wait()`、`notify()`和`notifyAll()`用于线程同步,`finalize()`在对象被垃圾回收时调用。掌握这些方法有助于更好地理解和使用Java中的对象行为。
|
2月前
|
Java 数据库
java小工具util系列1:日期和字符串转换工具
java小工具util系列1:日期和字符串转换工具
64 26
|
2月前
|
存储 缓存 安全
java 中操作字符串都有哪些类,它们之间有什么区别
Java中操作字符串的类主要有String、StringBuilder和StringBuffer。String是不可变的,每次操作都会生成新对象;StringBuilder和StringBuffer都是可变的,但StringBuilder是非线程安全的,而StringBuffer是线程安全的,因此性能略低。
71 8
|
2月前
|
安全 Java API
告别SimpleDateFormat:Java 8日期时间API的最佳实践
在Java开发中,处理日期和时间是一个基本而重要的任务。传统的`SimpleDateFormat`类因其简单易用而被广泛采用,但它存在一些潜在的问题,尤其是在多线程环境下。本文将探讨`SimpleDateFormat`的局限性,并介绍Java 8引入的新的日期时间API,以及如何使用这些新工具来避免潜在的风险。
43 5
|
2月前
|
安全 Java
Java多线程集合类
本文介绍了Java中线程安全的问题及解决方案。通过示例代码展示了使用`CopyOnWriteArrayList`、`CopyOnWriteArraySet`和`ConcurrentHashMap`来解决多线程环境下集合操作的线程安全问题。这些类通过不同的机制确保了线程安全,提高了并发性能。
|
2月前
|
存储 Java 程序员
Java基础的灵魂——Object类方法详解(社招面试不踩坑)
本文介绍了Java中`Object`类的几个重要方法,包括`toString`、`equals`、`hashCode`、`finalize`、`clone`、`getClass`、`notify`和`wait`。这些方法是面试中的常考点,掌握它们有助于理解Java对象的行为和实现多线程编程。作者通过具体示例和应用场景,详细解析了每个方法的作用和重写技巧,帮助读者更好地应对面试和技术开发。
145 4
|
2月前
|
Java 编译器 开发者
Java异常处理的最佳实践,涵盖理解异常类体系、选择合适的异常类型、提供详细异常信息、合理使用try-catch和finally语句、使用try-with-resources、记录异常信息等方面
本文探讨了Java异常处理的最佳实践,涵盖理解异常类体系、选择合适的异常类型、提供详细异常信息、合理使用try-catch和finally语句、使用try-with-resources、记录异常信息等方面,帮助开发者提高代码质量和程序的健壮性。
90 2
|
2月前
|
Java Android开发
Eclipse 创建 Java 类
Eclipse 创建 Java 类
32 0