• Java中时间工具类


    最近总结了一下时间相关的用法,如下。

    1、日期转换为字符串 默认"yyyy-MM-dd HH:mm:ss"

    2、任意类型日期字符串转时间

    3、获取当前对应格式的日期

    4、获取当前对应格式的日期 默认"yyyyMMddHHmmssSSS"

    5、计算该天是星期几

    6、获取星期几,java中一周中的数字 转 常规一周中的数字

    7、根据日期获取星期

    8、获取一个月的开始和结束时间

    9、获取一年的开始和结束时间

    10、获取季度

    11、获取某月 所有日期(yyyy-mm-dd格式字符串)

    12、获取一周的开始和结束时间

    13、获取某周 所有日期(yyyy-mm-dd格式字符串)

    14、 计算两个日期之间相差的秒数

    15、计算两个日期之间相差的天数

    16、根据日期判断是上午下午还是晚上

    17、获取该月有多少天

    18、计算开始时间和结束时间的差值,转成多少天

    ..........等等

    等等相关用方法,比较感兴趣,可以参照具体方法具体查看。

    1. import org.apache.commons.lang3.StringUtils;
    2. import org.springframework.util.Assert;
    3. import java.math.BigDecimal;
    4. import java.sql.Timestamp;
    5. import java.text.ParseException;
    6. import java.text.ParsePosition;
    7. import java.text.SimpleDateFormat;
    8. import java.time.LocalTime;
    9. import java.util.*;
    10. /**
    11. * 时间工具类
    12. */
    13. public class DateUtils {
    14. private static final String TIMESTAMP_FORMAT = "yyyy-MM-dd HH:mm:ss.SSS";
    15. private static final String DATETIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
    16. private static final String DATE_FORMAT = "yyyy-MM-dd";
    17. private static final String DATE_SIMPLE_FORMAT = "yyyyMMdd";
    18. //====================================时间转换=======================================>>
    19. /**
    20. * 时长转换
    21. *
    22. * @param time 通话时长(秒)
    23. * @return 几小时几分钟几秒
    24. */
    25. public static String getStrTime(Integer time) {
    26. if (time == null || time == 0) return "";
    27. StringBuilder str = new StringBuilder();
    28. int hour = time / 3600;
    29. if (hour != 0) str.append(hour).append("小时");
    30. int minutes = (time - hour * 3600) / 60;
    31. if (minutes != 0) str.append(minutes).append("分钟");
    32. int seconds = time - hour * 3600 - minutes * 60;
    33. if (seconds != 0) str.append(seconds).append("秒");
    34. return str.toString();
    35. }
    36. public static String millisToStr(long time) {
    37. if (time <= 0) return "0 秒";
    38. if (time < 1000) {
    39. return (time / 1000.0f) + "秒";
    40. }
    41. return getStrTime((int) time / 1000);
    42. }
    43. public static String millisDiff(long time) {
    44. return millisToStr(System.currentTimeMillis() - time);
    45. }
    46. /**
    47. * 日期转换为字符串 默认"yyyy-MM-dd HH:mm:ss"
    48. *
    49. * @param date 日期
    50. */
    51. public static String dateToStr(Date date) {
    52. return dateToStr(date, null);
    53. }
    54. /**
    55. * 日期转换为字符串
    56. *
    57. * @param date 日期
    58. * @param format 日期格式
    59. */
    60. public static String dateToStr(Date date, String format) {
    61. if (date == null) return null;
    62. // 如果没有指定字符串转换的格式,则用默认格式进行转换
    63. if (null == format || "".equals(format) || "Datetime".equals(format)) {
    64. format = DATETIME_FORMAT;
    65. } else if ("Timestamp".equals(format)) {
    66. format = TIMESTAMP_FORMAT;
    67. } else if ("Date".equals(format)) {
    68. format = DATE_FORMAT;
    69. } else if ("DateSimple".equals(format)) {
    70. format = DATE_SIMPLE_FORMAT;
    71. } else if ("Simple".equals(format)) {
    72. format = DATE_SIMPLE_FORMAT;
    73. }
    74. SimpleDateFormat sdf = new SimpleDateFormat(format);
    75. return sdf.format(date);
    76. }
    77. /**
    78. * 任意类型日期字符串转时间
    79. */
    80. public static Date strToDate(String time) {
    81. if (StringUtils.isBlank(time)) return null;
    82. SimpleDateFormat formatter;
    83. int tempPos = time.indexOf("AD");
    84. time = time.trim();
    85. formatter = new SimpleDateFormat("yyyy.MM.dd G 'at' hh:mm:ss z");
    86. if (tempPos > -1) {
    87. time = time.substring(0, tempPos) +
    88. "公元" + time.substring(tempPos + "AD".length());//china
    89. formatter = new SimpleDateFormat("yyyy.MM.dd G 'at' hh:mm:ss z");
    90. }
    91. if (time.contains(".")) time = time.replaceAll("\\.", "/");
    92. if (time.contains("-")) time = time.replaceAll("-", "/");
    93. if (!time.contains("/") && !time.contains(" ")) {
    94. formatter = new SimpleDateFormat("yyyyMMddHHmmss");
    95. } else if (time.contains("/")) {
    96. if (time.contains("am") || time.contains("pm")) formatter = new SimpleDateFormat("yyyy/MM/dd KK:mm:ss a");
    97. else if (time.contains(" ")) formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
    98. else {
    99. String[] dateArr = time.split("/");
    100. if (dateArr.length == 2 || (dateArr.length == 3 && StringUtils.isBlank(dateArr[2])))
    101. formatter = new SimpleDateFormat("yyyy/MM");
    102. else formatter = new SimpleDateFormat("yyyy/MM/dd");
    103. }
    104. }
    105. ParsePosition pos = new ParsePosition(0);
    106. return formatter.parse(time, pos);
    107. }
    108. public static Date strToDate(String time, String formatterString) {
    109. if (StringUtils.isBlank(time) || StringUtils.isBlank(formatterString)) return null;
    110. SimpleDateFormat formatter = new SimpleDateFormat(formatterString);
    111. ParsePosition pos = new ParsePosition(0);
    112. return formatter.parse(time, pos);
    113. }
    114. public static Date strToDateThrow(String time) {
    115. if (StringUtils.isBlank(time)) return null;
    116. Date value = strToDate(time);
    117. Assert.notNull(value, "无法识别日期格式: " + value);
    118. return value;
    119. }
    120. //====================================时间获取=======================================>>
    121. /**
    122. * 获取当前对应格式的日期
    123. */
    124. public static String getDateStr() {
    125. return getDateStr(null);
    126. }
    127. /**
    128. * 获取当前对应格式的日期 默认"yyyyMMddHHmmssSSS"
    129. *
    130. * @param format 日期格式
    131. */
    132. public static String getDateStr(String format) {
    133. if (null == format || "".equals(format)) {
    134. format = "yyyyMMddHHmmssSSS";
    135. }
    136. Date date = new Date();
    137. SimpleDateFormat df = new SimpleDateFormat(format);
    138. return df.format(date);
    139. }
    140. /**
    141. * 获取星期几,java中一周中的数字 转 常规一周中的数字
    142. * java中 周日=1 周六=7
    143. * eg:
    144. * 周一 -> 1
    145. * 周日 -> 7
    146. *
    147. * @param dayOfWeek java中一周中的数字
    148. */
    149. public static int getIsoDayOfWeek(int dayOfWeek) {
    150. int result;
    151. if (dayOfWeek == 1) {
    152. result = 7;
    153. } else {
    154. result = dayOfWeek - 1;
    155. }
    156. return result;
    157. }
    158. /**
    159. * 根据日期获取星期
    160. */
    161. public static String getWeekOfDate(Date date) {
    162. String[] weekDays = {"sun", "mon", "tue", "wed", "thu", "fri", "sat"};
    163. Calendar cal = Calendar.getInstance();
    164. cal.setTime(date);
    165. int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
    166. if (w < 0) w = 0;
    167. return weekDays[w];
    168. }
    169. //获取一个月的开始和结束时间
    170. public static List getMonthFirstAndEndDay(Date date) {
    171. List result = new ArrayList<>();
    172. Calendar c = Calendar.getInstance();
    173. c.setTime(date);
    174. c.set(Calendar.HOUR_OF_DAY, 0);
    175. c.set(Calendar.MINUTE, 0);
    176. c.set(Calendar.SECOND, 0);
    177. c.set(Calendar.MILLISECOND, 0);
    178. c.set(Calendar.DAY_OF_MONTH, 1);//设置为1号
    179. result.add(c.getTime());
    180. c.add(Calendar.MONTH, 1);//加一个月
    181. c.add(Calendar.MILLISECOND, -1);//减一毫秒
    182. result.add(c.getTime());
    183. return result;
    184. }
    185. //获取一年的开始和结束时间
    186. public static List getYearFirstAndEndDay(Date date) {
    187. List result = new ArrayList<>();
    188. Calendar c = Calendar.getInstance();
    189. c.setTime(date);
    190. c.set(Calendar.MONTH, 0);
    191. c.set(Calendar.DATE, 1);
    192. c.set(Calendar.HOUR_OF_DAY, 0);
    193. c.set(Calendar.MINUTE, 0);
    194. c.set(Calendar.SECOND, 0);
    195. c.set(Calendar.MILLISECOND, 0);
    196. result.add(c.getTime());
    197. c.add(Calendar.YEAR, 1);//加一年
    198. c.add(Calendar.MILLISECOND, -1);//减一毫秒
    199. result.add(c.getTime());
    200. return result;
    201. }
    202. public static Date getYearStartTime(Date date) {
    203. Calendar calendar = Calendar.getInstance();
    204. calendar.setTime(date);
    205. calendar.add(Calendar.YEAR, 0);
    206. calendar.add(Calendar.DATE, 0);
    207. calendar.add(Calendar.MONTH, 0);
    208. calendar.set(Calendar.DAY_OF_YEAR, 1);
    209. calendar.set(Calendar.HOUR_OF_DAY, 0);
    210. calendar.set(Calendar.MINUTE, 0);
    211. calendar.set(Calendar.SECOND, 0);
    212. calendar.set(Calendar.MILLISECOND, 0);
    213. return calendar.getTime();
    214. }
    215. /**
    216. * 获取季度
    217. */
    218. public static int getQuarter(Date date) {
    219. int quarter = 0;
    220. Calendar c = Calendar.getInstance();
    221. c.setTime(date);
    222. int month = c.get(Calendar.MONTH);
    223. switch (month) {
    224. case Calendar.JANUARY:
    225. case Calendar.FEBRUARY:
    226. case Calendar.MARCH:
    227. quarter = 1;
    228. break;
    229. case Calendar.APRIL:
    230. case Calendar.MAY:
    231. case Calendar.JUNE:
    232. quarter = 2;
    233. break;
    234. case Calendar.JULY:
    235. case Calendar.AUGUST:
    236. case Calendar.SEPTEMBER:
    237. quarter = 3;
    238. break;
    239. case Calendar.OCTOBER:
    240. case Calendar.NOVEMBER:
    241. case Calendar.DECEMBER:
    242. quarter = 4;
    243. break;
    244. }
    245. return quarter;
    246. }
    247. /**
    248. * 获取某月 所有日期(yyyy-mm-dd格式字符串)
    249. */
    250. public static List getMonthFullDay(Date date) {
    251. SimpleDateFormat dateFormatYYYYMMDD = new SimpleDateFormat(DATE_FORMAT);
    252. List fullDayList = new ArrayList<>();
    253. // 获得当前日期对象
    254. Calendar c = Calendar.getInstance();
    255. c.setTime(date);
    256. c.set(Calendar.HOUR_OF_DAY, 0);
    257. c.set(Calendar.MINUTE, 0);
    258. c.set(Calendar.SECOND, 0);
    259. c.set(Calendar.MILLISECOND, 0);
    260. // 当月1号
    261. c.set(Calendar.DAY_OF_MONTH, 1);
    262. int count = c.getActualMaximum(Calendar.DAY_OF_MONTH);
    263. for (int j = 1; j <= count; j++) {
    264. fullDayList.add(dateFormatYYYYMMDD.format(c.getTime()));
    265. c.add(Calendar.DAY_OF_MONTH, 1);
    266. }
    267. return fullDayList;
    268. }
    269. /**
    270. * 获取一周的开始和结束时间
    271. */
    272. public static List dateToWeekStartAndEnd(Date date) {
    273. List result = new ArrayList<>();
    274. Calendar c = Calendar.getInstance();
    275. c.setTime(date);
    276. c.set(Calendar.HOUR_OF_DAY, 0);
    277. c.set(Calendar.MINUTE, 0);
    278. c.set(Calendar.SECOND, 0);
    279. c.set(Calendar.MILLISECOND, 0);
    280. c.set(Calendar.DAY_OF_WEEK, 2);//设置为星期1
    281. result.add(c.getTime());
    282. c.add(Calendar.DAY_OF_WEEK_IN_MONTH, 1);//加一个周
    283. c.add(Calendar.MILLISECOND, -1);//减一毫秒
    284. result.add(c.getTime());
    285. return result;
    286. }
    287. /**
    288. * 获取某周 所有日期(yyyy-mm-dd格式字符串)
    289. */
    290. public static List getWeekFullDay(Date date) {
    291. SimpleDateFormat dateFormatYYYYMMDD = new SimpleDateFormat(DATE_FORMAT);
    292. List fullDayList = new ArrayList<>();
    293. // 获得当前日期对象
    294. Calendar c = Calendar.getInstance();
    295. c.setTime(date);
    296. c.set(Calendar.HOUR_OF_DAY, 0);
    297. c.set(Calendar.MINUTE, 0);
    298. c.set(Calendar.SECOND, 0);
    299. c.set(Calendar.MILLISECOND, 0);
    300. //周一
    301. c.set(Calendar.DAY_OF_WEEK, 2);
    302. int count = c.getActualMaximum(Calendar.DAY_OF_WEEK);
    303. for (int j = 1; j <= count; j++) {
    304. fullDayList.add(dateFormatYYYYMMDD.format(c.getTime()));
    305. c.add(Calendar.DAY_OF_WEEK, 1);
    306. }
    307. return fullDayList;
    308. }
    309. /**
    310. * 获取当前date的上周的周一
    311. */
    312. public static Date getLastWeekMonday(Date date) {
    313. Date monday = getWeekMonday(date);
    314. Date lastDate = getLastSec(monday);
    315. return getWeekMonday(lastDate);
    316. }
    317. /**
    318. * 获取当前date的所在周的周一
    319. */
    320. public static Date getWeekMonday(Date date) {
    321. Calendar calendar = new GregorianCalendar();
    322. calendar.setTime(date);
    323. calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
    324. calendar.set(Calendar.HOUR_OF_DAY, 0);
    325. calendar.set(Calendar.MINUTE, 0);
    326. calendar.set(Calendar.SECOND, 0);
    327. calendar.set(Calendar.MILLISECOND, 0);
    328. return calendar.getTime();
    329. }
    330. /**
    331. * 获取一天的开始时间和结束时间
    332. */
    333. public static List dateToDayStartAndEnd(Date date) {
    334. List result = new ArrayList<>();
    335. Calendar c = Calendar.getInstance();
    336. c.setTime(date);
    337. //将时分秒,毫秒域清零
    338. c.set(Calendar.HOUR_OF_DAY, 0);
    339. c.set(Calendar.MINUTE, 0);
    340. c.set(Calendar.SECOND, 0);
    341. c.set(Calendar.MILLISECOND, 0);
    342. result.add(c.getTime());
    343. c.add(Calendar.DAY_OF_YEAR, 1);
    344. c.add(Calendar.SECOND, -1);
    345. result.add(c.getTime());
    346. return result;
    347. }
    348. /**
    349. * 获取今天一天的开始时间和结束时间
    350. */
    351. public static List getToday() {
    352. return dateToDayStartAndEnd(new Date());
    353. }
    354. /**
    355. * 获取 时间段内 所有日期(yyyy-mm-dd格式字符串)
    356. */
    357. public static List getFullDay(Date startTime, Date endTime) {
    358. SimpleDateFormat dateFormatYYYYMMDD = new SimpleDateFormat(DATE_FORMAT);
    359. List fullDayList = new ArrayList<>();
    360. // 获得当前日期对象
    361. Calendar s = Calendar.getInstance();
    362. s.setTime(startTime);
    363. s.set(Calendar.HOUR_OF_DAY, 0);
    364. s.set(Calendar.MINUTE, 0);
    365. s.set(Calendar.SECOND, 0);
    366. s.set(Calendar.MILLISECOND, 0);
    367. Calendar e = Calendar.getInstance();
    368. e.setTime(endTime);
    369. e.set(Calendar.HOUR_OF_DAY, 0);
    370. e.set(Calendar.MINUTE, 0);
    371. e.set(Calendar.SECOND, 0);
    372. e.set(Calendar.MILLISECOND, 0);
    373. int daysBetween = getDaysBetween(s.getTime(), e.getTime());
    374. for (int i = 0; i <= daysBetween; i++) {
    375. fullDayList.add(dateFormatYYYYMMDD.format(s.getTime()));
    376. s.add(Calendar.DAY_OF_MONTH, 1);
    377. }
    378. return fullDayList;
    379. }
    380. //====================================时间计算=======================================>>
    381. /**
    382. * 计算两个日期之间相差的秒数
    383. *
    384. * @param smdate 较小的时间
    385. * @param bdate 较大的时间
    386. * @return 相差秒数
    387. */
    388. public static int getSecsBetween(Date smdate, Date bdate) {
    389. SimpleDateFormat sdf = new SimpleDateFormat(DATETIME_FORMAT);
    390. try {
    391. smdate = sdf.parse(sdf.format(smdate));
    392. bdate = sdf.parse(sdf.format(bdate));
    393. } catch (ParseException e) {
    394. e.printStackTrace();
    395. }
    396. Calendar cal = Calendar.getInstance();
    397. cal.setTime(smdate);
    398. long time1 = cal.getTimeInMillis();
    399. cal.setTime(bdate);
    400. long time2 = cal.getTimeInMillis();
    401. long between_days = (time2 - time1) / 1000;
    402. return Integer.parseInt(String.valueOf(between_days));
    403. }
    404. /**
    405. * 计算两个日期之间相差的天数
    406. *
    407. * @param smdate 较小的时间
    408. * @param bdate 较大的时间
    409. * @return 相差天数
    410. */
    411. public static int getDaysBetween(Date smdate, Date bdate) {
    412. int second = getSecsBetween(smdate, bdate);
    413. long between_days = second / 3600 / 24;
    414. return Integer.parseInt(String.valueOf(between_days));
    415. }
    416. /**
    417. * 根据日期判断是上午下午还是晚上
    418. *
    419. * @return 1:上午 2:下午 3:晚上
    420. */
    421. public static Integer getTimeByDate(Date date) {
    422. if (date == null) return null;
    423. Calendar c = Calendar.getInstance();
    424. c.setTime(date);
    425. int hour = c.get(Calendar.HOUR_OF_DAY);
    426. if (hour <= 12) return 1;
    427. else if (hour <= 18) return 2;
    428. else return 3;
    429. }
    430. /**
    431. * 该天是否为月末最后一天
    432. */
    433. public static boolean isLastDayOfMonth(Date date) {
    434. Calendar calendar = Calendar.getInstance();
    435. calendar.setTime(date);
    436. calendar.set(Calendar.DATE, (calendar.get(Calendar.DATE) + 1));
    437. return calendar.get(Calendar.DAY_OF_MONTH) == 1;
    438. }
    439. /**
    440. * 获取该月有多少天
    441. */
    442. public static int getDaysOfMonth(Date date) {
    443. Calendar calendar = Calendar.getInstance();
    444. calendar.setTime(date);
    445. return calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
    446. }
    447. /**
    448. * 计算得到2个时间的差值,并转成中文
    449. *
    450. * @param startDate 开始时间
    451. * @param endDate 结束时间
    452. */
    453. public static String getDateDiff(Date startDate, Date endDate) {
    454. long nd = 1000 * 24 * 60 * 60;
    455. long nh = 1000 * 60 * 60;
    456. long nm = 1000 * 60;
    457. long ns = 1000;
    458. //long ns = 1000;
    459. //获得两个时间的毫秒时间差异
    460. long diff = endDate.getTime() - startDate.getTime();
    461. //计算差多少天
    462. long day = diff / nd;
    463. //计算差多少小时
    464. long hour = diff % nd / nh;
    465. //计算差多少分钟
    466. long min = diff % nd % nh / nm;
    467. //计算差多少秒//输出结果
    468. long sec = diff % nd % nh % nm / ns;
    469. String result = "";
    470. if (day > 0) result += day + "天";
    471. if (hour > 0) result += hour + "小时";
    472. if (min > 0) result += min + "分钟";
    473. if (result.isEmpty()) result = sec + "秒";
    474. return result;
    475. }
    476. /**
    477. * 计算开始时间和结束时间的差值,转成多少小时
    478. *
    479. * @param startDate 开始时间
    480. * @param endDate 结束时间
    481. * @return eg: 3.21 (小时)
    482. */
    483. public static BigDecimal getDateDiffHour(Date startDate, Date endDate) {
    484. BigDecimal nh = new BigDecimal(1000 * 60 * 60);
    485. BigDecimal diff = new BigDecimal(endDate.getTime() - startDate.getTime());
    486. return diff.divide(nh, 2, BigDecimal.ROUND_HALF_UP);
    487. }
    488. /**
    489. * 计算开始时间和结束时间的差值,转成多少天
    490. *
    491. * @param startDate 开始时间
    492. * @param endDate 结束时间
    493. * @return eg: 3.21 (天)
    494. */
    495. public static BigDecimal getDateDiffDay(Date startDate, Date endDate) {
    496. BigDecimal nh = new BigDecimal(1000 * 60 * 60 * 24);
    497. BigDecimal diff = new BigDecimal(endDate.getTime() - startDate.getTime());
    498. return diff.divide(nh, 2, BigDecimal.ROUND_HALF_UP);
    499. }
    500. //====================================获取时间段=======================================>>
    501. /**
    502. * 获取这一周的date,从周一到周日
    503. */
    504. public static List dateToWeek(Date mdate) {
    505. Calendar c = Calendar.getInstance();
    506. c.setTime(mdate);
    507. int b = c.get(Calendar.DAY_OF_WEEK) - 1;
    508. Date fdate;
    509. List list = new ArrayList<>();
    510. long fTime = mdate.getTime() - b * 24 * 3600000;
    511. for (int a = 1; a <= 7; a++) {
    512. fdate = new Date();
    513. fdate.setTime(fTime + (a * 24 * 3600000));
    514. list.add(a - 1, fdate);
    515. }
    516. return list;
    517. }
    518. /**
    519. * 获取前几天的date
    520. */
    521. public static List getDateListBefore(Date date, Integer num) {
    522. if (date == null) return null;
    523. List result = new ArrayList<>();
    524. Calendar c = Calendar.getInstance();
    525. c.setTime(date);
    526. c.add(Calendar.DATE, -num);
    527. for (int a = 1; a <= num; a++) {
    528. c.add(Calendar.DATE, 1);
    529. Date temp = c.getTime();
    530. result.add(temp);
    531. }
    532. return result;
    533. }
    534. /**
    535. * 获取一周、月、年的date
    536. */
    537. public static List getDateListByKind(Date date, String kind) {
    538. if (date == null || kind == null) return null;
    539. Calendar end = Calendar.getInstance();
    540. Calendar c = Calendar.getInstance();
    541. c.setFirstDayOfWeek(Calendar.MONDAY);
    542. c.setTime(date);
    543. //将时分秒,毫秒域清零
    544. c.set(Calendar.HOUR_OF_DAY, 0);
    545. c.set(Calendar.MINUTE, 0);
    546. c.set(Calendar.SECOND, 0);
    547. c.set(Calendar.MILLISECOND, 0);
    548. switch (kind) {
    549. case "week":
    550. c.add(Calendar.DATE, c.getFirstDayOfWeek() - c.get(Calendar.DAY_OF_WEEK));
    551. end.setTime(c.getTime());
    552. end.add(Calendar.DATE, 7);
    553. break;
    554. case "month":
    555. c.set(Calendar.DAY_OF_MONTH, 1);
    556. end.setTime(c.getTime());
    557. end.add(Calendar.MONTH, 1);
    558. break;
    559. case "half":
    560. c.add(Calendar.MONTH, -6);
    561. c.set(Calendar.DAY_OF_MONTH, 1);
    562. end.setTime(date);
    563. end.set(Calendar.DAY_OF_MONTH, 1);
    564. end.add(Calendar.MONTH, 1);
    565. end.add(Calendar.DAY_OF_MONTH, -1);
    566. break;
    567. case "year":
    568. c.set(Calendar.DAY_OF_YEAR, 1);
    569. end.setTime(c.getTime());
    570. end.add(Calendar.YEAR, 1);
    571. break;
    572. default:
    573. return null;
    574. }
    575. boolean setSec = false;
    576. List result = new ArrayList<>();
    577. while (c.before(end)) {
    578. if (result.size() != 0 && !setSec) {
    579. //将时分秒,毫秒域清零
    580. c.set(Calendar.HOUR_OF_DAY, 23);
    581. c.set(Calendar.MINUTE, 59);
    582. c.set(Calendar.SECOND, 59);
    583. c.set(Calendar.MILLISECOND, 999);
    584. setSec = true;
    585. }
    586. result.add(c.getTime());
    587. c.add(Calendar.DATE, 1);
    588. }
    589. return result;
    590. }
    591. //====================================修改时间=======================================>>
    592. /**
    593. * 获取前一秒
    594. */
    595. public static Date getLastSec(Date date) {
    596. if (date == null) return null;
    597. Calendar c = Calendar.getInstance();
    598. c.setTime(date);
    599. c.add(Calendar.SECOND, -1);
    600. return c.getTime();
    601. }
    602. /**
    603. * 添加秒
    604. */
    605. public static Date getWhichSecs(Date date, int secs) {
    606. if (date == null) return null;
    607. Calendar c = Calendar.getInstance();
    608. c.setTime(date);
    609. c.add(Calendar.SECOND, secs);
    610. return c.getTime();
    611. }
    612. /**
    613. * 添加分
    614. */
    615. public static Date getWhichMinute(Date date, int minute) {
    616. if (date == null) return null;
    617. Calendar c = Calendar.getInstance();
    618. c.setTime(date);
    619. c.add(Calendar.MINUTE, minute);
    620. return c.getTime();
    621. }
    622. /**
    623. * 获取后一天
    624. */
    625. public static Date getNextDate(Date date) {
    626. return addDay(date, 1);
    627. }
    628. /**
    629. * 添加天
    630. */
    631. public static Date addDay(Date date, Integer day) {
    632. if (date == null || day == null) return null;
    633. Calendar c = Calendar.getInstance();
    634. c.setTime(date);
    635. c.add(Calendar.DATE, day);
    636. return c.getTime();
    637. }
    638. /**
    639. * 添加月
    640. */
    641. public static Date addMonth(Date date, Integer month) {
    642. if (date == null || month == null) return null;
    643. if (month == 0) return date;
    644. Calendar c = Calendar.getInstance();
    645. c.setTime(date);
    646. c.add(Calendar.MONTH, month);
    647. return c.getTime();
    648. }
    649. /**
    650. * 添加年
    651. */
    652. public static Date addYear(Date date, Integer year) {
    653. if (date == null || year == null) return null;
    654. Calendar c = Calendar.getInstance();
    655. c.setTime(date);
    656. c.add(Calendar.YEAR, year);
    657. return c.getTime();
    658. }
    659. /**
    660. * 清除时分秒
    661. */
    662. public static Date clearTime(Date date) {
    663. Calendar c = Calendar.getInstance();
    664. c.setTime(date);
    665. //将时分秒,毫秒域清零
    666. c.set(Calendar.HOUR_OF_DAY, 0);
    667. c.set(Calendar.MINUTE, 0);
    668. c.set(Calendar.SECOND, 0);
    669. c.set(Calendar.MILLISECOND, 0);
    670. return c.getTime();
    671. }
    672. /**
    673. * 清除秒
    674. */
    675. public static Date clearSec(Date date) {
    676. Calendar c = Calendar.getInstance();
    677. c.setTime(date);
    678. c.set(Calendar.SECOND, 0);
    679. c.set(Calendar.MILLISECOND, 0);
    680. return c.getTime();
    681. }
    682. /**
    683. * 将时分秒设置成当前时间
    684. */
    685. public static Date setTimeToNow(Date date) {
    686. return setTime(date, new Date());
    687. }
    688. /**
    689. * 将时分秒设置成新时间
    690. */
    691. public static Date setTime(Date date, Date newDate) {
    692. if (date == null) return null;
    693. Calendar c = Calendar.getInstance();
    694. c.setTime(date);
    695. Calendar now = Calendar.getInstance();
    696. now.setTime(newDate);
    697. //将时分秒,毫秒域清零
    698. c.set(Calendar.HOUR_OF_DAY, now.get(Calendar.HOUR_OF_DAY));
    699. c.set(Calendar.MINUTE, now.get(Calendar.MINUTE));
    700. c.set(Calendar.SECOND, now.get(Calendar.SECOND));
    701. c.set(Calendar.MILLISECOND, now.get(Calendar.MILLISECOND));
    702. return c.getTime();
    703. }
    704. /**
    705. * Timestamp时间戳转date
    706. *
    707. * @param timestamp 时间戳
    708. */
    709. public static Date timeToDate(Timestamp timestamp) {
    710. // Timestamp -> String
    711. SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    712. String dateString = formatter.format(timestamp);
    713. return DateUtils.strToDate(dateString);
    714. }
    715. public static boolean isWorkTime() {
    716. LocalTime now = LocalTime.now();
    717. return (now.isAfter(LocalTime.of(5, 0)) && now.isBefore(LocalTime.of(18, 0))) ||
    718. now.isAfter(LocalTime.of(0, 0)) && now.isBefore(LocalTime.of(1, 0));
    719. }
    720. public static String ehrTimeTransform(String time) {
    721. if (StringUtils.isBlank(time)) return null;
    722. String format;
    723. if (time.length() == 8) {
    724. format = "yyyyMMdd";
    725. } else if (time.length() == 14) {
    726. format = "yyyyMMddHHmmss";
    727. } else {
    728. format = "yyyy-MM-dd HH:mm:ss";
    729. }
    730. return DateUtils.dateToStr(DateUtils.strToDate(time, format), "yyyy-MM-dd HH:mm:ss");
    731. }
    732. public static void awaitFreeTime() {
    733. while (isWorkTime()) {
    734. try {
    735. Thread.sleep(600000);
    736. } catch (InterruptedException e) {
    737. throw new IllegalArgumentException("任务等待失败");
    738. }
    739. }
    740. System.out.println("等待结束");
    741. }
    742. }

    以上就是时间相关的处理的方法,感兴趣的可以看看

  • 相关阅读:
    树莓派4B_OpenCv学习笔记15:OpenCv定位物体实时坐标
    基于AlexNet卷积神经网络的手写体数字倾斜校正系统研究-附Matlab代码
    redhat7.6安装weblogic12c
    nginx的location的优先级和匹配方式和nginx的重定向
    Vue3基础——数据双向绑定、常用指令、计算属性、watch监听数据变化、class类名&style样式多种操作方式
    Servlet开发-session和cookie理解案例-登录页面
    【小笔记】基于SpringBoot使用WebSocket进行前后端通信
    linux如何查看各个文件夹大小
    二叉树的OJ题——C++
    用visa进行仪表通信
  • 原文地址:https://blog.csdn.net/ProBaiXiaodi/article/details/126977770