使用Java 8 Time API获取第一次和最后一次(以毫秒为单位)
我将我的时间计算从自我实现的代码转换为
Java 8 Time API.
我需要从java.time.Year或java.time.Month类开始和结束时间(以毫秒为单位),我计划稍后在另一层中使用JFreeChart. 我需要像getFirstMillisecond()和amp;来自org.jfree.data.time.RegularTimePeriod类的JFreeChart的getLastMilliSecond(). 我已经实现了类似的代码 – public static long getStartTimeInMillis(java.time.Year year,java.time.Month month) { if (year != null && month != null) { return LocalDate.of(year.getValue(),month,1).with(TemporalAdjusters.firstDayOfMonth()). atStartOfDay().atZone(TimeZone.getDefault().toZoneId()).toInstant().toEpochMilli(); } else if (year != null) { return LocalDate.of(year.getValue(),java.time.Month.JANUARY,1).with(TemporalAdjusters.firstDayOfMonth()). atStartOfDay().atZone(TimeZone.getDefault().toZoneId()).toInstant().toEpochMilli(); } return 0; } public static long getEndTimeInMillis(java.time.Year year,java.time.Month month) { if (year != null && month != null) { return LocalDate.of(year.getValue(),1).with(TemporalAdjusters.lastDayOfMonth()). atTime(OffsetTime.MAX).toLocalDateTime().atZone(TimeZone.getDefault().toZoneId()).toInstant().toEpochMilli(); } else if (year != null) { return LocalDate.of(year.getValue(),java.time.Month.DECEMBER,1).with(TemporalAdjusters.lastDayOfMonth()). atTime(OffsetTime.MAX).toLocalDateTime().atZone(TimeZone.getDefault().toZoneId()).toInstant().toEpochMilli(); } return 0; } 但它看起来真的很复杂.有没有更好/更短的方法来获得这些价值? 解决方法
YearMonth
是的,有一个更好的方法.使用java.time附带的 此外,将该调用链分解为单独的语句,以使其更易读,更容易跟踪/调试.信任JVM以代表您进行优化;只使用调用链,使代码更易读,更容易理解. 通过TimeZone获取JVM的当前默认时区是不必要的.相反,请致电 设置一些输入值. // Inputs Year year = Year.of ( 2015 ); Month month = Month.DECEMBER; 你方法的核心部分. // Code for your method. YearMonth yearMonth = year.atMonth ( month ); // Instantiate a YearMonth from a Year and a Month. LocalDate localDate = yearMonth.atDay ( 1 ); // First day of month. ZoneId zoneId = ZoneId.systemDefault (); // Or… ZoneId.of("America/Montreal"); ZonedDateTime zdt = localDate.atStartOfDay ( zoneId ); long millis = zdt.toInstant ().toEpochMilli (); 转储到控制台. System.out.println ( "year: " + year + " | month: " + month + " | yearMonth: " + yearMonth + " | zoneId:" + zoneId + " | zdt: " + zdt + " | millis: " + millis );
更好的是,将YearMonth实例传递给您的方法,而不是一对Year和Month对象.如果您的其他业务逻辑使用Year Year对,请使用YearMonth – 这就是它的用途. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |