Get the first and last time (in milliseconds) using the Java 8 time API
I converted my time calculation from self implemented code to Java 8 time API
I need from Java time. Year or Java time. The start and end times of the month class (in milliseconds), and I plan to use JfreeChart. Com later in another layer
I need things like getfirstmillisecond () and amp; From org jfree. data. time. Getlastmillisecond() of JfreeChart of regulartimeperiod class
I have implemented similar code –
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; }
But it looks really complicated Is there a better / shorter way to get these values?
Solution
YearMonth
Yes, there is a better way Using Java Time comes with the Yearmonth class
In addition, the call chain is decomposed into separate statements to make it easier to read and track / debug Trust the JVM to optimize on your behalf; Using only call chains makes the code easier to read and understand
It is unnecessary to obtain the current default time zone of the JVM through timezone Instead, call zoneid systemDefault().
Set some input values
// Inputs Year year = Year.of ( 2015 ); Month month = Month.DECEMBER;
The core of your approach
// 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 ();
Dump to console
System.out.println ( "year: " + year + " | month: " + month + " | yearMonth: " + yearMonth + " | zoneId:" + zoneId + " | zdt: " + zdt + " | millis: " + millis );
Better yet, pass the Yearmonth instance to your method instead of a pair of year and month objects If your other business logic uses year year pairs, use Yearmonth – that's what it's used for