Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.time.Period to seconds

How to convert java.time.Period to seconds?

The code below produces unexpected results

java.time.Period period = java.time.Period.parse( "P1M" );
final long days = period.get( ChronoUnit.DAYS ); // produces 0
final long seconds = period.get( ChronoUnit.SECONDS ); // throws exception

I am looking for the Java 8 equivalent to:

// import javax.xml.datatype.DatatypeFactory;
// import javax.xml.datatype.Duration;

DatatypeFactory datatypeFactory = DatatypeFactory.newInstance();
Duration d1 = datatypeFactory.newDuration( "P1M" ); 
final long sec = d1.getTimeInMillis( new Date() ) / 1000;
like image 907
Seweryn Habdank-Wojewódzki Avatar asked Nov 04 '25 10:11

Seweryn Habdank-Wojewódzki


1 Answers

As it says in the documentation, Period is a period of time expressed in days, months, and years; your example is "one month."

The number of seconds in a month is not a fixed value. February has 28 or 29 days while December has 31, so "one month" from (say) February 12th has fewer seconds than "one month" from December 12th. On occasion (such as last year), there's a leap second in December. Depending on the time zone and month, it might have an extra 30 minutes, hour, or hour and a half; or that much less than usual, thanks to going into or out of daylight saving time.

You can only ask "Starting from this date in this timezone, how many seconds are there in the next [period] of time?" (or alternately, "How many seconds in the last [period] before [date-with-timezone]?") You can't ask it without a reference point, it doesn't make sense. (You've now updated the question to add a reference point: "now".)

If we introduce a reference point, then you can use a Temporal (like LocalDateTime or ZonedDateTime) as your reference point and use its until method with ChronoUnit.MILLIS. For example, in local time starting from "now":

LocalDateTime start = LocalDateTime.now();
Period period = Period.parse("P1M");
LocalDateTime end = start.plus(period);
long milliseconds = start.until(end, ChronoUnit.MILLIS);
System.out.println(milliseconds);

Live Copy

Naturally, that can be more concise, I wanted to show each step. More concise:

LocalDateTime start = LocalDateTime.now();
System.out.println(start.until(start.plus(Period.parse("P1M")), ChronoUnit.MILLIS));
like image 89
T.J. Crowder Avatar answered Nov 07 '25 04:11

T.J. Crowder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!