简体   繁体   中英

Convert a floating-point number of seconds to milliseconds using JodaTime / java.time

An API I'm calling returns a duration as a fractional number of seconds:

double seconds = someOtherApi.getDuration();

To convert it to milliseconds we could do:

long millis = (long) (seconds * 1000);

However we use JodaTime in our codebase and would prefer to leave any sort of conversion work up to the library. Unfortunately I don't see an appropriate factory method in JodaTime that takes a double .

Is there a "proper" way to convert a fractional duration value into a Joda Duration , or is doing so manually the best option?

You need to register a converter. Create a class that implements the DurationConverter interface and register it with the ConverterManager.

Here's an example (I tested with JodaTime 2.10):

Converter code:

import org.joda.time.convert.DurationConverter;

public class DurationConverterFromDouble implements DurationConverter {

    @Override
    public Class<?> getSupportedType() {
        return Double.class;
    }

    @Override
    public long getDurationMillis(Object objectDouble) {
        return (int)(((double)objectDouble) * 1000);
    }
}

Code:

// register the converter
ConverterManager.getInstance().addDurationConverter(new DurationConverterFromDouble());

// create Duration from a double:
double d = 3.14;
Duration jodaDuration = new Duration(d);
System.out.println("Joda duration is " + jodaDuration);
System.out.println("Joda duration in milliseconds is " + jodaDuration.getMillis());

Output:

 Joda duration is PT3.140S Joda duration in milliseconds is 3140 

Interestingly, NodaTime (equivalent library for C#) does not require to use a converter to create a Duration directly from a double. I fired up a new C# console project, downloaded NodaTime 2.3.0, played around with the API via intellisense (autocomplete), and found this solution:

Code:

double d = 3.14;
var nodaDuration = Duration.FromSeconds(d);
Console.WriteLine("Noda duration is " + nodaDuration);
Console.WriteLine("Noda duration in milliseconds is " + nodaDuration.TotalMilliseconds);

Output:

 Noda duration is 0:00:00:03.14 Noda duration in milliseconds is 3140 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM