End*_*ery 4 java jfreechart java-8 java-time
我正在将时间计算从自我实现的代码转换为Java 8 Time API。
我需要一个java.time.Year或java.time.Month类的开始和结束时间(以毫秒为单位),我计划稍后在另一层中使用JFreeChart。
我需要一个像功能getFirstMillisecond()及getLastMilliSecond()从org.jfree.data.time.RegularTimePeriod类的JFreeChart的。
我已经实现了类似以下的代码:
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(), month, 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;
}
Run Code Online (Sandbox Code Playgroud)
但这对我来说真的很复杂。有没有更好/更短的方法来获取这些值?
YearMonth是的,有一种更好的方法。使用YearMonthjava.time附带的类。
另外,将该调用链分解为单独的语句,以使其更具可读性,并且更易于跟踪/调试。信任JVM代表您进行优化;仅在使代码更易读和易于理解的地方使用调用链接。
不需要TimeZone获取JVM当前的默认时区。而是致电ZoneId.systemDefault()。
设置一些输入值。
// Inputs
Year year = Year.of ( 2015 );
Month month = Month.DECEMBER;
Run Code Online (Sandbox Code Playgroud)
方法的核心部分。
// 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 ();
Run Code Online (Sandbox Code Playgroud)
转储到控制台。
System.out.println ( "year: " + year + " | month: " + month + " | yearMonth: " + yearMonth + " | zoneId:" + zoneId + " | zdt: " + zdt + " | millis: " + millis );
Run Code Online (Sandbox Code Playgroud)
年份:2015 | 月份:12月| 年月:2015-12 | zoneId:America / Los_Angeles | zdt:2015-12-01T00:00-08:00 [美国/洛杉矶] | Millis:1448956800000
更好的是,将YearMonth实例传递给您的方法,而不是一对Year和Month对象。如果您的其他业务逻辑使用Year+ Month对,请YearMonth改用–这就是它的用途。
| 归档时间: |
|
| 查看次数: |
507 次 |
| 最近记录: |