gpt4 book ai didi

java - 使用 Java 8 Time API 获取第一次和最后一次时间(以毫秒为单位)

转载 作者:行者123 更新时间:2023-12-02 06:42:02 25 4
gpt4 key购买 nike

我正在将时间计算从自行实现的代码转换为 Java 8 Time API。

我需要从 java.time.Yearjava.time.Month 类获取以毫秒为单位的开始时间和结束时间,我计划稍后使用它们JFreeChart 的另一层。

我需要 JFreeChart 的 org.jfree.data.time.RegularTimePeriod 类中的 getFirstMillisecond()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(), 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;
}

但对我来说这看起来真的很复杂。有没有更好/更短的方法来获取这些值?

最佳答案

年月

是的,有一个稍微好一点的方法。使用YearMonth java.time 中包含的类。

此外,将该调用链分解为单独的语句,以使其更具可读性且更易于跟踪/调试。相信 JVM 会代表您进行优化;仅在使代码更具可读性和更容易理解的情况下使用调用链。

不需要通过TimeZone来获取JVM当前的默认时区。相反,请调用 ZoneId.systemDefault() .

设置一些输入值。

// 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 );

year: 2015 | month: DECEMBER | yearMonth: 2015-12 | zoneId:America/Los_Angeles | zdt: 2015-12-01T00:00-08:00[America/Los_Angeles] | millis: 1448956800000

更好的是,将 YearMonth 实例传递给您的方法,而不是一对 YearMonth 对象。如果您的其他业务逻辑使用 Year + Month 对,请使用 YearMonth - 这就是它的用途。

关于java - 使用 Java 8 Time API 获取第一次和最后一次时间(以毫秒为单位),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34432718/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com