简体   繁体   English

使用JodaTime / java.time将浮点数秒转换为毫秒

[英]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: 我正在调用的API将持续时间返回为小数秒:

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. 但是我们在代码库中使用JodaTime,并且希望将任何类型的转换工作留给库。 Unfortunately I don't see an appropriate factory method in JodaTime that takes a double . 不幸的是,我没有在JodaTime中看到一个合适的工厂方法需要一个double

Is there a "proper" way to convert a fractional duration value into a Joda Duration , or is doing so manually the best option? 是否有“正确”的方法将小数持续时间值转换为Joda Duration ,或者手动将其作为最佳选项?

You need to register a converter. 您需要注册转换器。 Create a class that implements the DurationConverter interface and register it with the ConverterManager. 创建一个实现DurationConverter接口的类,并使用ConverterManager注册它。

Here's an example (I tested with JodaTime 2.10): 这是一个例子(我用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. 有趣的是,NodaTime(C#的等效库)不需要使用转换器直接从double创建Duration。 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: 我启动了一个新的C#控制台项目,下载了NodaTime 2.3.0,通过intellisense(自动完成)使用API​​,并找到了这个解决方案:

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 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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