年月日时间戳和年月日互相转换,时分秒时间戳和时分秒互相转化

- 日理万妓 2022-02-27 12:20 595阅读 0赞

其中要用的工具包:

  1. <dependency>
  2. <groupId>cn.hutool</groupId>
  3. <artifactId>hutool-all</artifactId>
  4. <version>4.5.1</version>
  5. </dependency>
  6. /**
  7. * 将秒数转成hh:mm:ss的时间
  8. * @param time
  9. * @return
  10. */
  11. public static String TimeToString(long time){
  12. SimpleDateFormat sf = new SimpleDateFormat("HH:mm:ss");
  13. sf.setTimeZone(TimeZone.getTimeZone("GTM+0"));
  14. return sf.format(time*1000);
  15. }
  16. /**
  17. * 将格式为HH:mm:ss的时间转成时间戳(从00:00:00开始计算)
  18. * @param time
  19. * @return
  20. * @throws Exception
  21. */
  22. public static int StringToTime(String time) throws Exception {
  23. SimpleDateFormat sf = new SimpleDateFormat("HH:mm:ss");
  24. sf.setTimeZone(TimeZone.getTimeZone("GTM+0"));
  25. Date parse2 = sf.parse(time);
  26. return Convert.toInt((parse2.getTime()) / 1000);
  27. }
  28. /**
  29. * 将格式为 HH:mm:ss - HH:mm:ss的字符串转成一个时间戳的数组
  30. * @param srt
  31. * @return
  32. * @throws Exception
  33. */
  34. public static Integer[] toStringToTime(Object srt) throws Exception {
  35. String s1 = srt.toString();
  36. String[] s = s1.split("-");
  37. Integer[] l = new Integer[2];
  38. l[0] = StringToTime(s[0]);
  39. l[1] = StringToTime(s[1]);
  40. return l;
  41. }
  42. /**
  43. * 将前端传来的时间字符转化成两个分为开始时间和结束时间
  44. * @param str 格式 yyyy-MM-dd - yyyy-MM-dd
  45. * @return
  46. */
  47. public static Long[] SplitDate(Object str) {
  48. String s = str.toString();
  49. String[] split = s.split(" - ");
  50. long begin = StringToTimestamp(split[0], "yyyy-MM-dd HH:mm:ss");
  51. long end = StringToTimestamp(split[1], "yyyy-MM-dd HH:mm:ss");
  52. Long[] arra = {begin, end};
  53. return arra;
  54. }
  55. /**
  56. * 将时间形式的字符串转成时间戳
  57. *yyyy-MM-dd
  58. * @return
  59. */
  60. public static long StringToTimestamp(String time, String format) {
  61. LocalDateTime parse1 = LocalDateTime.parse(time, DateTimeFormatter.ofPattern(format));
  62. ZoneId zone = ZoneId.systemDefault();
  63. Instant instant = parse1.atZone(zone).toInstant();
  64. Long l = instant.toEpochMilli();
  65. String s = l.toString();
  66. String sub = StrUtil.sub(s, 0, -3);
  67. return Long.parseLong(sub);
  68. }

发表评论

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

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

相关阅读