关键词搜索

源码搜索 ×
×

Java JDK1.8时间区间计算类Period和Duration

发布2020-09-29浏览1501次

详情内容

在Java项目中,时间格式化在很多时候都会用到。在JDK1.8之前我们都是通过自己封装的时间工具类来实现,在1.8之后我们可以使用它提供的Period和Duration来实现时间区间和转换计算。使用这两个工具,我们可以计算年、月、日、周、天、时、分、秒、纳秒等。

目录

传统封装Util工具

Period时间区间计算

Duration时间计算


传统封装Util工具

这种工具类在项目中非常普遍:

  1. package com.patrol.beans.util;
  2. import java.text.ParseException;
  3. import java.text.SimpleDateFormat;
  4. import java.util.Calendar;
  5. import java.util.Date;
  6. /**
  7. * 日期工具类
  8. *
  9. * @author PJL
  10. */
  11. public class DateUtil {
  12. /**
  13. * 格式化日期和时间
  14. */
  15. public static SimpleDateFormat sdfTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  16. /**
  17. * 格式化日期
  18. */
  19. public static SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd");
  20. /**
  21. * 获取当前日期yyyy-MM-dd
  22. *
  23. * @return
  24. */
  25. public static String getDate() {
  26. return sdfDate.format(new Date());
  27. }
  28. /**
  29. * 获取当前日期
  30. *
  31. * @return
  32. */
  33. public static String getCurrentDate() {
  34. Calendar c = Calendar.getInstance();
  35. int year = c.get(Calendar.YEAR);
  36. int month = c.get(Calendar.MONTH) + 1;
  37. int day = c.get(Calendar.DATE);
  38. return "" + year + "-" + month + "-" + day;
  39. }
  40. /**
  41. * 获取当前日期和时间
  42. *
  43. * @return
  44. */
  45. public static String getCurrentDateTime() {
  46. Calendar c = Calendar.getInstance();
  47. int year = c.get(Calendar.YEAR);
  48. int month = c.get(Calendar.MONTH) + 1;
  49. int day = c.get(Calendar.DATE);
  50. int hour = c.get(Calendar.HOUR_OF_DAY);
  51. int minute = c.get(Calendar.MINUTE);
  52. int second = c.get(Calendar.SECOND);
  53. return "" + year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second;
  54. }
  55. /**
  56. * 获取当前日期前若干天或者后若干天的日期
  57. *
  58. * @param dayCount ,天数,正数为之后,负数为之前
  59. * @return
  60. */
  61. public static String getIntervalDay(int dayCount) {
  62. //SimpleDateFormat dft = new SimpleDateFormat("yyyy-MM-dd");
  63. Date beginDate = new Date();
  64. Calendar date = Calendar.getInstance();
  65. date.setTime(beginDate);
  66. date.set(Calendar.DATE, date.get(Calendar.DATE) + dayCount);
  67. return sdfDate.format(date.getTime());
  68. }
  69. /**
  70. * 获取昨天的日期
  71. *
  72. * @return
  73. */
  74. public static String getYesterdayDate() {
  75. return getIntervalDay(-1);
  76. }
  77. /**
  78. * 获取今天的日期
  79. *
  80. * @return
  81. */
  82. public static String getTodayDate() {
  83. return getIntervalDay(0);
  84. }
  85. /**
  86. * 获取明天的日期
  87. *
  88. * @return
  89. */
  90. public static String getTomorrowDate() {
  91. return getIntervalDay(1);
  92. }
  93. /**
  94. * 获取明天的时间LONG
  95. *
  96. * @return
  97. */
  98. public static Long getTomorrowTime() {
  99. String tomorrowDate = DateUtil.getTomorrowDate();
  100. return DateUtil.getSpecifiedDayTime(tomorrowDate);
  101. }
  102. /**
  103. * 获取日期时间
  104. *
  105. * @param dateTime
  106. * @return
  107. */
  108. public static Long getLongTime(String dateTime) {
  109. Calendar c = Calendar.getInstance();
  110. Date date = null;
  111. try {
  112. date = sdfTime.parse(dateTime);
  113. } catch (ParseException e) {
  114. e.printStackTrace();
  115. }
  116. return date.getTime();
  117. }
  118. /**
  119. * 获得指定日期的前一天
  120. *
  121. * @param specifiedDay
  122. * @return
  123. * @throws Exception
  124. */
  125. public static String getSpecifiedDayBefore(String specifiedDay) {
  126. // SimpleDateFormat simpleDateFormat = new
  127. // SimpleDateFormat("yyyy-MM-dd");
  128. Calendar c = Calendar.getInstance();
  129. Date date = null;
  130. try {
  131. date = sdfDate.parse(specifiedDay);
  132. } catch (ParseException e) {
  133. e.printStackTrace();
  134. }
  135. c.setTime(date);
  136. int day = c.get(Calendar.DATE);
  137. c.set(Calendar.DATE, day - 1);
  138. String dayBefore = sdfDate.format(c.getTime());
  139. return dayBefore;
  140. }
  141. /**
  142. * 获得指定日期的后一天
  143. *
  144. * @param specifiedDay
  145. * @return
  146. */
  147. public static String getSpecifiedDayAfter(String specifiedDay) {
  148. Calendar c = Calendar.getInstance();
  149. Date date = null;
  150. try {
  151. date = sdfDate.parse(specifiedDay);
  152. } catch (ParseException e) {
  153. e.printStackTrace();
  154. }
  155. c.setTime(date);
  156. int day = c.get(Calendar.DATE);
  157. c.set(Calendar.DATE, day + 1);
  158. String dayAfter = sdfDate.format(c.getTime());
  159. return dayAfter;
  160. }
  161. /**
  162. * 获取指定日期的时间LONG类型
  163. *
  164. * @param specifiedDay
  165. * @return
  166. */
  167. public static Long getSpecifiedDayTime(String specifiedDay) {
  168. Date date = null;
  169. try {
  170. date = sdfDate.parse(specifiedDay);
  171. } catch (ParseException e) {
  172. e.printStackTrace();
  173. }
  174. return date.getTime();
  175. }
  176. /**
  177. * 获取时差日期和时间
  178. *
  179. * @param time 负数向前时间,正数向后时间
  180. * @return
  181. */
  182. public static String getDateTime(Date date, long time) {
  183. date.setTime(time);
  184. return sdfTime.format(date);
  185. }
  186. /**
  187. * 增加或减少当前日期的毫秒数
  188. *
  189. * @param pastOrFutureTime 负数向前时间,正数向后时间
  190. * @return
  191. */
  192. public static String getAddDateTime(long pastOrFutureTime) {
  193. Date date = new Date();
  194. pastOrFutureTime = date.getTime() + pastOrFutureTime;
  195. date.setTime(pastOrFutureTime);
  196. return sdfTime.format(date);
  197. }
  198. /**
  199. * 时间毫秒设置日期格式化
  200. *
  201. * @param time
  202. * @return
  203. */
  204. public static String setDateTime(long time) {
  205. Date date = new Date();
  206. date.setTime(time);
  207. return sdfTime.format(date);
  208. }
  209. }

传统封装模式,对时间计算不够灵活,不能完全覆盖所有业务场景,需要的时候还得修改这个工具类。 

Period时间区间计算

创建Period有以下方式:

  • ZERO 空
  • between
  • of*

下面是一个Period Junit示例:

  1. package com.forestar.patrol;
  2. import lombok.extern.slf4j.Slf4j;
  3. import org.junit.Assert;
  4. import org.junit.Test;
  5. import java.time.LocalDate;
  6. import java.time.Period;
  7. /**
  8. * @Copyright: 2019-2021
  9. * @FileName: PeriodTest.javaPJL
  10. * @Author:
  11. * @Date: 2020/9https://files.jxasp.com/image/29 8:37
  12. * @Description: 时间差区间计算
  13. */
  14. @Slf4j
  15. public class PeriodTest {
  16. /**
  17. * 常用方法
  18. */
  19. @Test
  20. public void test(){
  21. log.info("method ============================test()");
  22. LocalDate startDate = LocalDate.of(2020, 9, 20);
  23. LocalDate endDate = LocalDate.of(2020, 12, 29);
  24. log.info("yyyy-MM-dd = {}",(startDate.getYear()+"-"+startDate.getMonth().getValue()+"-"+startDate.getDayOfMonth()));
  25. log.info("yyyy-MM-dd = {}",(endDate.getYear()+"-"+endDate.getMonth().getValue()+"-"+endDate.getDayOfMonth()));
  26. Period periodZero = Period.ZERO;
  27. Period periodYMD = Period.of(20,3,1);
  28. Period periodYear = Period.ofYears(1);
  29. Period periodMonth = Period.ofMonths(2);
  30. Period periodDay = Period.ofDays(2);
  31. Period periodWeek = Period.ofWeeks(23);
  32. Period period = Period.between(startDate, endDate);
  33. log.info("isZero() = {}",period.isZero());
  34. log.info("isNegative() = {}",period.isNegative());
  35. log.info("getYears() = {}",period.getYears());
  36. log.info("getMonths() = {}",period.getMonths());
  37. log.info("getDays() = {}",period.getDays());
  38. log.info("getUnits() = {}",period.getUnits());
  39. log.info("getChronology() = {}",period.getChronology());
  40. log.info("withYears(1) = {}",period.withYears(1));// P1Y9D
  41. log.info("withMonths(1) = {}",period.withMonths(1));//P1M9D
  42. log.info("withDays(1) = {}",period.withDays(1));//P1D
  43. log.info("toString() = {}",period.toString());
  44. }
  45. /**
  46. * 创建Period[注意周期不是具体的年月日而是差值]
  47. */
  48. @Test
  49. public void createPeriod(){
  50. log.info("method ============================createPeriod()");
  51. Period fromCharYears = Period.parse("P2020Y");
  52. Assert.assertEquals(2020, fromCharYears.getYears());
  53. log.info("getYears() = {}",fromCharYears.getYears());
  54. Period fromCharUnits = Period.parse("P2020Y9M29D");
  55. Assert.assertEquals(29, fromCharUnits.getDays());
  56. log.info("getDays() = {}",fromCharUnits.getDays());
  57. }
  58. /**
  59. * 计算加减
  60. */
  61. @Test
  62. public void calculate(){
  63. log.info("method ============================calculate()");
  64. Period period = Period.parse("P9M56D");
  65. int days = period.plusDays(50).getDays();
  66. log.info("getDays() = {}",days);
  67. int months = period.minusMonths(2).getMonths();
  68. log.info("getMonths() = {}",months);
  69. }
  70. }

输出结果:

  1. 2020-09-29 09:35:45.026 [main] INFO com.forestar.patrol.PeriodTest | method ============================calculate()
  2. 2020-09-29 09:35:45.084 [main] INFO com.forestar.patrol.PeriodTest | getDays() = 106
  3. 2020-09-29 09:35:45.090 [main] INFO com.forestar.patrol.PeriodTest | getMonths() = 7
  4. 2020-09-29 09:35:45.100 [main] INFO com.forestar.patrol.PeriodTest | method ============================test()
  5. 2020-09-29 09:35:45.108 [main] INFO com.forestar.patrol.PeriodTest | yyyy-MM-dd = 2020-9-20
  6. 2020-09-29 09:35:45.108 [main] INFO com.forestar.patrol.PeriodTest | yyyy-MM-dd = 2020-12-29
  7. 2020-09-29 09:35:45.265 [main] INFO com.forestar.patrol.PeriodTest | isZero() = false
  8. 2020-09-29 09:35:45.265 [main] INFO com.forestar.patrol.PeriodTest | isNegative() = false
  9. 2020-09-29 09:35:45.265 [main] INFO com.forestar.patrol.PeriodTest | getYears() = 0
  10. 2020-09-29 09:35:45.265 [main] INFO com.forestar.patrol.PeriodTest | getMonths() = 3
  11. 2020-09-29 09:35:45.266 [main] INFO com.forestar.patrol.PeriodTest | getDays() = 9
  12. 2020-09-29 09:35:45.266 [main] INFO com.forestar.patrol.PeriodTest | getUnits() = [Years, Months, Days]
  13. 2020-09-29 09:35:45.280 [main] INFO com.forestar.patrol.PeriodTest | getChronology() = ISO
  14. 2020-09-29 09:35:45.280 [main] INFO com.forestar.patrol.PeriodTest | withYears(1) = P1Y3M9D
  15. 2020-09-29 09:35:45.280 [main] INFO com.forestar.patrol.PeriodTest | withMonths(1) = P1M9D
  16. 2020-09-29 09:35:45.280 [main] INFO com.forestar.patrol.PeriodTest | withDays(1) = P3M1D
  17. 2020-09-29 09:35:45.281 [main] INFO com.forestar.patrol.PeriodTest | toString() = P3M9D
  18. 2020-09-29 09:35:45.281 [main] INFO com.forestar.patrol.PeriodTest | method ============================createPeriod()
  19. 2020-09-29 09:35:45.281 [main] INFO com.forestar.patrol.PeriodTest | getYears() = 2020
  20. 2020-09-29 09:35:45.282 [main] INFO com.forestar.patrol.PeriodTest | getDays() = 29

Duration时间计算

 使用Duration.of*(param)初始化一个Duration实例。

下面是一个Duration Junit测试示例:

  1. package com.forestar.patrol;
  2. import lombok.extern.slf4j.Slf4j;
  3. import org.junit.Test;
  4. import java.time.Duration;
  5. /**
  6. * @Copyright: 2019-2021
  7. * @FileName: DurationTest.java
  8. * @Author: PJL
  9. * @Date: 2020/9https://files.jxasp.com/image/29 9:03
  10. * @Description: 时间计算
  11. */
  12. @Slf4j
  13. public class DurationTest {
  14. @Test
  15. public void test(){
  16. //86400是一天的秒计算量
  17. Duration d = Duration.ofSeconds(86400);
  18. log.info("getSeconds() = {}",d.getSeconds());
  19. log.info("getNano() = {}",d.getNano());
  20. log.info("getUnits() = {}",d.getUnits());
  21. log.info("isNegative() = {}",d.isNegative());
  22. log.info("isZero() = {}",d.isZero());
  23. log.info("toDays() = {}",d.toDays());
  24. log.info("toHours() = {}",d.toHours());
  25. log.info("toMinutes() = {}",d.toMinutes());
  26. log.info("toNanos() = {}",d.toNanos());
  27. log.info("toMillis() = {}",d.toMillis());
  28. log.info("toString() = {}",d.toString());
  29. }
  30. }

测试输出结果:

  1. 2020-09-29 09:52:07.650 [main] INFO com.forestar.patrol.DurationTest | getSeconds() = 86400
  2. 2020-09-29 09:52:07.730 [main] INFO com.forestar.patrol.DurationTest | getNano() = 0
  3. 2020-09-29 09:52:07.732 [main] INFO com.forestar.patrol.DurationTest | getUnits() = [Seconds, Nanos]
  4. 2020-09-29 09:52:07.732 [main] INFO com.forestar.patrol.DurationTest | isNegative() = false
  5. 2020-09-29 09:52:07.732 [main] INFO com.forestar.patrol.DurationTest | isZero() = false
  6. 2020-09-29 09:52:07.733 [main] INFO com.forestar.patrol.DurationTest | toDays() = 1
  7. 2020-09-29 09:52:07.733 [main] INFO com.forestar.patrol.DurationTest | toHours() = 24
  8. 2020-09-29 09:52:07.734 [main] INFO com.forestar.patrol.DurationTest | toMinutes() = 1440
  9. 2020-09-29 09:52:07.734 [main] INFO com.forestar.patrol.DurationTest | toNanos() = 86400000000000
  10. 2020-09-29 09:52:07.735 [main] INFO com.forestar.patrol.DurationTest | toMillis() = 86400000
  11. 2020-09-29 09:52:07.737 [main] INFO com.forestar.patrol.DurationTest | toString() = PT24H

 JDK为我们提供了这样的功能,既然知道了就尽量使用吧。

相关技术文章

点击QQ咨询
开通会员
返回顶部
×
微信扫码支付
微信扫码支付
确定支付下载
请使用微信描二维码支付
×

提示信息

×

选择支付方式

  • 微信支付
  • 支付宝付款
确定支付下载