Javax.measure.quantity.Duration conversion issue

1.3k views Asked by At

I am using javax.measure to convert user input to seconds that can vary anywhere from seconds to days, however converting from any unit to another doesn't work, here is what I have set up.

String units = "d";
double value = 30.0;
BaseUnit<Duration> unitType = new BaseUnit<Duration>(units);
UnitConverter toSeconds = unitType.getConverterTo(NonSI.DAY);
double s = toSeconds.convert(Measure.valueOf(value, unitType).doubleValue(unitType));

But I get this error

Exception in thread "main" javax.measure.converter.ConversionException: d is not compatible with s
at javax.measure.unit.Unit.searchConverterTo(Unit.java:259)
at javax.measure.unit.Unit.getConverterTo(Unit.java:248)
at FAMain.main(FAMain.java:18

This error comes up for any combination regardless if it is NonSI to NonSI. I can convert Length any way just fine, but for some reason Unit doesn't work.

1

There are 1 answers

4
Iłya Bursov On BEST ANSWER

the main problem that you cannot just create new BaseUnit<Duration>("d"); and suppose that it will somehow become NonSI.DAY.

probably here is the starting point:

public static double toSeconds(final String unit, final double value) {
    switch (unit.toLowerCase()) {
    case "d":
    case "day":
        return NonSI.DAY.getConverterTo(SI.SECOND).convert(value);
    case "m":
    case "minute":
        return NonSI.MINUTE.getConverterTo(SI.SECOND).convert(value);
    case "s":
    case "second":
        return value;
    default:
        throw new IllegalArgumentException(unit);
    }
}