Sebastian
Sebastian

Reputation: 795

Converting JodaTime Duration to Java 8 time Duration: getStandardMinutes and other methods

We're trying to convert a product that we have written using Joda-Time library to Java time due to some time zone wonkery in our country. (Daylight Saving Time DST is never consistent, and Joda-Time requires special manipulation and the use of offsets to get it to work properly).

I'm working with Joda-Time's Duration. There are a number of methods such as getStandardMinutes.

Is there an easy way to achieve the same functionality on the Java 8+ java.time Duration? I'm assuming based on the code and comments that Duration::toMinutes will not necessarily return the desired value.

Upvotes: 2

Views: 373

Answers (2)

Basil Bourque
Basil Bourque

Reputation: 338516

java.time.Duration = count of nanoseconds

As TreffnonX already answered, a Duration in java.time represents a span-of-time not attached to the timeline on a scale of 24-hour-days (without regard for calendar), hours, minutes, seconds, and fraction of a second. In other words, a java.time.Duration is just a count of nanoseconds with a bunch of handy methods.

Span-of-time classes

Here is a graphical table I made to help orient you to the various span-of-time classes built into Java 8 and later, plus classes from the ThreeTen-Extra library.

FYI, all three projects (Joda-Time, java-time, and ThreeTen-Extra) are led by the same man, Stephen Colebourne.

Table of span-of-time classes in Java and in the ThreeTen-Extra project

Upvotes: 2

TreffnonX
TreffnonX

Reputation: 2930

In Java 8's Duration class, a duration contains no reference date. Therefore all minutes you will extract are standard minutes. In JodaTime the comments for getStandardXXX specify explicitly, that a Duration assumes default length of day (24h/day, 60min/hour, 60sec/min ...). However this is only relevant, if you would want to apply a duration to a reference (date)time (for example, add this Duration to this DateTime), in which case adding a 'day' to a date flipping on daylight saving time might have unexpected effects (like an hour offset). However, for the Duration object this is irrelevant, as it effectively represents simply a duration in nanoseconds in 'real time', disregarding timezones and thelike.

In essence, you can use toMinutes() to get the exact amount of minutes as long value.

From the javadoc:

Gets the number of minutes in this duration.

This returns the total number of minutes in the duration by dividing the number of seconds by 60.

This instance is immutable and unaffected by this method call.

Upvotes: 4

Related Questions