java时间工具类

今天药忘吃喽~ 2021-09-28 01:18 448阅读 0赞

在项目中,很多地方需要根据时间获取相应的数据,将时间格式化,或者时间比较等相关操作。一个良好的工具类不仅可以减少代码冗余,还能促进业务处理,加快进度。

  1. /**
  2. * @author: lxw
  3. * @Date: 2018/12/25 14:36
  4. * @Description: 时间工具类
  5. */
  6. public class DateUtils {
  7. /**
  8. * 常用时间格式
  9. */
  10. public final static String DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss";
  11. public final static String MONTH_PATTERN = "yyyy-MM";
  12. public final static String DATE_PATTERN = "yyyy-MM-dd";
  13. public final static String HH_MM_SS = "HH:mm:ss";
  14. public final static String DATE_PATTERN_YYYY_MM_DD_HH_MM = "yyyy-MM-dd HH:mm";
  15. public static String DATE_TIME_PATTERN_YYYY_MM_DD_HH_MM_SS_SSS = "yyyyMMddHHmmssSSS";
  16. public static String DATE_TIME_PATTERN_YYYY_MM_DD_HH_MM_SS = "yyyyMMddHHmmss";
  17. /**
  18. * 日期转换格式数组
  19. */
  20. public static String[][] regularExp = new String[][]{
  21. // 默认格式
  22. {"\\d{4}-((([0][1,3-9]|[1][0-2]|[1-9])-([0-2]\\d|[3][0,1]|[1-9]))|((02|2)-(([1-9])|[0-2]\\d)))\\s+([0,1]\\d|[2][0-3]|\\d):([0-5]\\d|\\d):([0-5]\\d|\\d)",
  23. DATE_TIME_PATTERN},
  24. // 仅日期格式 年月日
  25. {"\\d{4}-((([0][1,3-9]|[1][0-2]|[1-9])-([0-2]\\d|[3][0,1]|[1-9]))|((02|2)-(([1-9])|[0-2]\\d)))",
  26. DATE_PATTERN},
  27. // 带毫秒格式
  28. {"\\d{4}((([0][1,3-9]|[1][0-2]|[1-9])([0-2]\\d|[3][0,1]|[1-9]))|((02|2)(([1-9])|[0-2]\\d)))([0,1]\\d|[2][0-3])([0-5]\\d|\\d)([0-5]\\d|\\d)\\d{1,3}",
  29. DATE_TIME_PATTERN_YYYY_MM_DD_HH_MM_SS_SSS}
  30. };
  31. /**
  32. * 日期转换为String类型
  33. *
  34. * @param date 日期
  35. * @param pattern 获取格式
  36. * @return String
  37. */
  38. public static String format(Date date, String pattern) {
  39. if (date != null) {
  40. SimpleDateFormat df = new SimpleDateFormat(pattern);
  41. return df.format(date);
  42. }
  43. return null;
  44. }
  45. /**
  46. * 日期转换为String类型,并添加或减少相应的天数
  47. *
  48. * @param date 日期
  49. * @param pattern 获取格式
  50. * @param amount 天数
  51. * @return String
  52. */
  53. public static String format(Date date, String pattern, int amount) {
  54. if (date != null) {
  55. Calendar calendar = Calendar.getInstance();
  56. calendar.setTime(date);
  57. calendar.add(Calendar.DAY_OF_MONTH, amount);
  58. SimpleDateFormat df = new SimpleDateFormat(pattern);
  59. return df.format(calendar.getTime());
  60. }
  61. return null;
  62. }
  63. /**
  64. * 字符串转换成日期
  65. *
  66. * @param strDate 日期字符串
  67. * @param pattern 日期的格式
  68. * @return data
  69. */
  70. public static Date stringToDate(String strDate, String pattern) {
  71. if (StringUtils.isBlank(strDate)) {
  72. return null;
  73. }
  74. DateTimeFormatter fmt = DateTimeFormat.forPattern(pattern);
  75. return fmt.parseLocalDateTime(strDate).toDate();
  76. }
  77. /**
  78. * 两个时间之间的天数
  79. *
  80. * @param date1
  81. * @param date2
  82. * @param pattern 格式
  83. * @return 天数
  84. */
  85. public static long getDays(String date1, String date2, String pattern) {
  86. SimpleDateFormat formatter = new SimpleDateFormat(pattern);
  87. if (date1 == null || date1.equals("")) {
  88. return 0;
  89. }
  90. if (date2 == null || date2.equals("")) {
  91. return 0;
  92. }
  93. try {
  94. Date date = formatter.parse(date1);
  95. Date newDate = formatter.parse(date2);
  96. return (date.getTime() - newDate.getTime()) / (24 * 60 * 60 * 1000);
  97. } catch (Exception e) {
  98. }
  99. return 0;
  100. }
  101. /**
  102. * 产生周序列,即得到当前时间所在的年度是第几周
  103. *
  104. * @return
  105. */
  106. public static String getSeqWeek() {
  107. Calendar c = Calendar.getInstance(Locale.CHINA);
  108. String week = Integer.toString(c.get(Calendar.WEEK_OF_YEAR));
  109. if (week.length() == 1) {
  110. week = "0" + week;
  111. }
  112. return week;
  113. }
  114. /**
  115. * 日期格式字符串转换成时间戳
  116. *
  117. * @param date_str 字符串日期
  118. * @param format 日期格式,如:yyyy-MM-dd HH:mm:ss
  119. * @return
  120. */
  121. public static String dateTimeStamp(String date_str, String format) {
  122. try {
  123. SimpleDateFormat sdf = new SimpleDateFormat(format);
  124. return String.valueOf(sdf.parse(date_str).getTime() / 1000);
  125. } catch (Exception e) {
  126. e.printStackTrace();
  127. }
  128. return "";
  129. }
  130. /**
  131. * 获取日期的格式
  132. *
  133. * @param date_str 日期格式字符串
  134. * @return 当前日期格式
  135. */
  136. public static String getDateFormat(String date_str) {
  137. String style = null;
  138. if (org.springframework.util.StringUtils.isEmpty(date_str)) {
  139. return null;
  140. }
  141. boolean b = false;
  142. for (int i = 0; i < regularExp.length; i++) {
  143. b = date_str.matches(regularExp[i][0]);
  144. if (b) {
  145. style = regularExp[i][1];
  146. }
  147. }
  148. if (org.springframework.util.StringUtils.isEmpty(style)) {
  149. return null;
  150. }
  151. return style;
  152. }
  153. /**
  154. * 转换为时间类型格式
  155. *
  156. * @param strDate 日期
  157. * @return
  158. */
  159. public static Date strToDate(String strDate) {
  160. try {
  161. String strType = getDateFormat(strDate);
  162. if (strType == null) {
  163. return null;
  164. }
  165. SimpleDateFormat sf = new SimpleDateFormat(strType);
  166. return new Date((sf.parse(strDate).getTime()));
  167. } catch (Exception e) {
  168. return null;
  169. }
  170. }
  171. /**
  172. * 获取两个字符串时间差
  173. *
  174. * @param beginTime 开始时间
  175. * @param endTime 结束时间
  176. * @return xx小时xx分钟
  177. */
  178. public static String timeLength(String beginTime, String endTime) {
  179. if (beginTime == null || "".equals(beginTime)) {
  180. return "";
  181. }
  182. if (endTime == null || "".equals(endTime)) {
  183. return "";
  184. }
  185. Date begin = DateUtils.strToDate(beginTime);
  186. Date end = DateUtils.strToDate(endTime);
  187. if (begin == null || end == null) {
  188. return "";
  189. }
  190. try {
  191. //除以1000是为了转换成秒
  192. long between = (end.getTime() - begin.getTime()) / 1000;
  193. int day = (int) between / (24 * 3600);
  194. int hour = (int) between % (24 * 3600) / 3600;
  195. int minute = (int) between % 3600 / 60;
  196. int currentHour = day * 24 + hour;
  197. return currentHour + "小时" + minute + "分钟";
  198. } catch (Exception e) {
  199. return "";
  200. }
  201. }
  202. /**
  203. * 判断是否润年
  204. *
  205. * @param date 日期
  206. * @return boolean
  207. */
  208. public static boolean isLeapYear(Date date) {
  209. /**
  210. * 1.被400整除是闰年
  211. * 2.不能被4整除则不是闰年
  212. * 3.能被4整除同时不能被100整除则是闰年
  213. * 4.能被4整除同时能被100整除则不是闰年
  214. */
  215. GregorianCalendar gc = (GregorianCalendar) Calendar.getInstance();
  216. gc.setTime(date);
  217. int year = gc.get(Calendar.YEAR);
  218. if ((year % 400) == 0) {
  219. return true;
  220. } else if ((year % 4) == 0) {
  221. if ((year % 100) == 0) {
  222. return false;
  223. } else {
  224. return true;
  225. }
  226. } else {
  227. return false;
  228. }
  229. }
  230. /**
  231. * 取得当前时间生成格式为yyyymmddhhmmss+k位随机数
  232. *
  233. * @param k 随机数位数
  234. */
  235. public static String getNo(int k) {
  236. Date date = new Date();
  237. return format(date, DATE_TIME_PATTERN_YYYY_MM_DD_HH_MM_SS) + getRandom(k);
  238. }
  239. /**
  240. * 返回一个随机数
  241. *
  242. * @param num 随机生成的位数
  243. * @return
  244. */
  245. public static String getRandom(int num) {
  246. Random random = new Random();
  247. if (num == 0) {
  248. return "";
  249. }
  250. String randomNum = "";
  251. for (int i = 0; i < num; i++) {
  252. //取0-9的随机数进行拼接
  253. randomNum += random.nextInt(9);
  254. }
  255. return randomNum;
  256. }
  257. /**
  258. * 根据周数,获取开始日期、结束日期
  259. *
  260. * @param week 周期 0本周,-1上周,-2上上周,1下周,2下下周
  261. * @return 返回date[0]开始日期、date[1]结束日期
  262. */
  263. public static Date[] getWeekStartAndEnd(int week) {
  264. DateTime dateTime = new DateTime();
  265. LocalDate date = new LocalDate(dateTime.plusWeeks(week));
  266. date = date.dayOfWeek().withMinimumValue();
  267. Date beginDate = date.toDate();
  268. Date endDate = date.plusDays(6).toDate();
  269. return new Date[]{beginDate, endDate};
  270. }
  271. /**
  272. * 对日期的【秒】进行加/减
  273. *
  274. * @param date 日期
  275. * @param seconds 秒数,负数为减
  276. * @return 加/减几秒后的日期
  277. */
  278. public static Date addDateSeconds(Date date, int seconds) {
  279. DateTime dateTime = new DateTime(date);
  280. return dateTime.plusSeconds(seconds).toDate();
  281. }
  282. /**
  283. * 对日期的【分钟】进行加/减
  284. *
  285. * @param date 日期
  286. * @param minutes 分钟数,负数为减
  287. * @return 加/减几分钟后的日期
  288. */
  289. public static Date addDateMinutes(Date date, int minutes) {
  290. DateTime dateTime = new DateTime(date);
  291. return dateTime.plusMinutes(minutes).toDate();
  292. }
  293. /**
  294. * 对日期的【小时】进行加/减
  295. *
  296. * @param date 日期
  297. * @param hours 小时数,负数为减
  298. * @return 加/减几小时后的日期
  299. */
  300. public static Date addDateHours(Date date, int hours) {
  301. DateTime dateTime = new DateTime(date);
  302. return dateTime.plusHours(hours).toDate();
  303. }
  304. /**
  305. * 对日期的【天】进行加/减
  306. *
  307. * @param date 日期
  308. * @param days 天数,负数为减
  309. * @return 加/减几天后的日期
  310. */
  311. public static Date addDateDays(Date date, int days) {
  312. DateTime dateTime = new DateTime(date);
  313. return dateTime.plusDays(days).toDate();
  314. }
  315. /**
  316. * 对日期的【周】进行加/减
  317. *
  318. * @param date 日期
  319. * @param weeks 周数,负数为减
  320. * @return 加/减几周后的日期
  321. */
  322. public static Date addDateWeeks(Date date, int weeks) {
  323. DateTime dateTime = new DateTime(date);
  324. return dateTime.plusWeeks(weeks).toDate();
  325. }
  326. /**
  327. * 对日期的【月】进行加/减
  328. *
  329. * @param date 日期
  330. * @param months 月数,负数为减
  331. * @return 加/减几月后的日期
  332. */
  333. public static Date addDateMonths(Date date, int months) {
  334. DateTime dateTime = new DateTime(date);
  335. return dateTime.plusMonths(months).toDate();
  336. }
  337. /**
  338. * 对日期的【年】进行加/减
  339. *
  340. * @param date 日期
  341. * @param years 年数,负数为减
  342. * @return 加/减几年后的日期
  343. */
  344. public static Date addDateYears(Date date, int years) {
  345. DateTime dateTime = new DateTime(date);
  346. return dateTime.plusYears(years).toDate();
  347. }
  348. /**
  349. * 比较时间大小
  350. *
  351. * @param exprtime 时间1
  352. * @param times 时间2
  353. * @return 0:时间相等 1;时间1在时间2之后 -1:时间1在时间2之前
  354. */
  355. public static int compareDate(String exprtime, String times) {
  356. int result = 0;
  357. //判断时间大小
  358. if (exprtime != null && !"".equals(exprtime)) {
  359. DateFormat dateFormat = new SimpleDateFormat(DATE_TIME_PATTERN);
  360. try {
  361. Date d1 = dateFormat.parse(exprtime);
  362. Date d2 = dateFormat.parse(times);
  363. if (d1.getTime() > d2.getTime()) {
  364. System.out.println(d1 + "在" + d2 + "之后");
  365. result = 1;
  366. } else if (d1.getTime() < d2.getTime()) {
  367. result = -1;
  368. System.out.println(d1 + "在" + d2 + "之前");
  369. } else {
  370. System.out.println(d1 + "=" + d2);
  371. }
  372. } catch (ParseException e) {
  373. e.printStackTrace();
  374. System.out.println("方法——compareDate异常");
  375. }
  376. }
  377. return result;
  378. }
  379. /**
  380. * 获取距离现在的天数
  381. *
  382. * @param exprtime 某天的时间字符串
  383. * @return 天数
  384. */
  385. public static long getDays(String exprtime) {
  386. Date begin = DateUtils.strToDate(format(new Date(), DATE_TIME_PATTERN));
  387. Date end = DateUtils.strToDate(exprtime);
  388. long between = (end.getTime() - begin.getTime()) / 1000;
  389. int day = (int) between / (24 * 3600);
  390. return day;
  391. }

测试类方法:

  1. public static void main(String[] args) {
  2. Date date = new Date();
  3. String dateString = DateUtils.format(date, DATE_TIME_PATTERN);
  4. System.out.println("时间格式转换为:" + dateString);
  5. String tomorrow = DateUtils.format(date, DATE_TIME_PATTERN, 1);
  6. System.out.println("明天日期:" + tomorrow);
  7. Date stringToDate = DateUtils.stringToDate(dateString, DATE_TIME_PATTERN);
  8. System.out.println("当天日期格式:" + stringToDate);
  9. boolean flag = DateUtils.isLeapYear(date);
  10. System.out.println("当前是否为闰年:" + flag);
  11. long days = DateUtils.getDays(tomorrow, dateString, DATE_PATTERN);
  12. System.out.println("天数相差:" + days + " 天");
  13. String getSeqWeek = DateUtils.getSeqWeek();
  14. System.out.println("今年第 " + getSeqWeek + " 周");
  15. String randomNum = DateUtils.getNo(4);
  16. System.out.println("编号:" + randomNum);
  17. String dateTimeStamp = DateUtils.dateTimeStamp(dateString, DATE_TIME_PATTERN);
  18. System.out.println("当期时间戳:" + dateTimeStamp);
  19. String timeLength = DateUtils.timeLength(dateString, tomorrow);
  20. System.out.println("相差时间:" + timeLength);
  21. String getDateFormat = DateUtils.getDateFormat(dateString);
  22. System.out.println("当前日期格式:" + getDateFormat);
  23. String stmpString = DateUtils.stampToDate("1545732716");
  24. System.out.println("当前日期:" + stmpString);
  25. String stmpLong = DateUtils.stampToDate(1545732716L);
  26. System.out.println("当前日期:" + stmpLong);
  27. long day = DateUtils.getDays("2019-01-01 18:20:20");
  28. System.out.println("距离当前时间:" + day + "天");
  29. }

输出结果:

  1. 时间格式转换为:2018-12-25 18:21:23
  2. 明天日期:2018-12-26 18:21:23
  3. 当天日期格式:Tue Dec 25 18:21:23 CST 2018
  4. 当前是否为闰年:false
  5. 天数相差:1
  6. 今年第 52
  7. 编号:201812251821237084
  8. 当期时间戳:1545733283
  9. 相差时间:24小时0分钟
  10. 当前日期格式:yyyy-MM-dd HH:mm:ss
  11. 当前日期:1970-01-19 05:22:12
  12. 当前日期:1970-01-19 05:22:12
  13. 距离当前时间:6

该类希望可以满足大部分的业务需求,后续如果还有会继续添加到下文中。

发表评论

表情:
评论列表 (有 0 条评论,448人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Java 时间工具

    借鉴网上资源与工作中经验整理的时间工具类(主要针对java.util.Date的使用,java8后的时间工具下期整理),欢迎大家一起完善补充。 import

    相关 Java时间工具

    该时间工具类功能:时间戳格式化至毫秒、时间戳格式化至秒、时间戳格式化至日、时间戳格式化成时和分、Date对象格式化至毫秒、Date对象格式化至秒、Date对象格式化至日、Da

    相关 java时间工具

    在项目中,很多地方需要根据时间获取相应的数据,将时间格式化,或者时间比较等相关操作。一个良好的工具类不仅可以减少代码冗余,还能促进业务处理,加快进度。 /