Reputation: 2177
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;
Upvotes: 4
Views: 9764
Reputation: 1075885
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);
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));
Upvotes: 12
Reputation: 1
The "get" method accepts only ChronoUnit.YEARS, ChronoUnit.MONTHS and ChronoUnit.DAYS.
Upvotes: -2