Search code examples
javatimetimeunit

TimeUnit on floating values


I created method like this, where I have 2 inputs.

first is type (e.g. 'd', 'h')
second is value (e.g. "15", "0.5")

I created function to convert it to minutes like this:

public Float toMinutes(char type, String value) {
    Float minutes = 0f;
    switch (type) {
        case 'd': {
            minutes += Integer.parseInt(value) * 1440;
            break;
        }
        case 'h': {
            minutes += Float.parseFloat(value) * 60;
            break;
        }
        case 'm': {
            minutes += Integer.parseInt(value);
            break;
        }
        default: {
            return 0f;
        }
    }
    return minutes;
}

I decided to refactor it, because those multiplication looks "ugly" for me. I found a better solution called TimeUnit.

public Long toMinutes(char type, String value) {
        Long minutesCounted = 0l;
        TimeUnit tu = TimeUnit.MINUTES;
        switch (type) {
            case 'd': {
                minutesCounted += tu.convert(Long.parseLong(value), TimeUnit.DAYS);
                break;
            }
            case 'h': {
                minutesCounted += tu.convert(Long.parseLong(value), TimeUnit.HOURS);
                break;
            }
            case 'm': {
                minutesCounted += tu.convert(Long.parseLong(value), TimeUnit.MINUTES);
                break;
            }
            default: {
                return 0l;
            }
        }
    return minutesCounted;
}

The problem is that this converter allow only long values, so now it works only on inputs like 15h and it will not work on inputs like 1,5h. Any ideas how to improve my solution to work with floating numbers?


Solution

  • Instead of using magic constants, you could use TimeUnit to figure out the conversion rate for 1 d, h, etc. to minutes like this

    public float toMinutes(char type, String value) {
        switch (type) {
            case 'd':
                return Integer.parseInt(value) * TimeUnit.DAYS.toMinutes(1);
            case 'h':
                return Float.parseFloat(value) * TimeUnit.HOURS.toMinutes(1);
            case 'm':
                return Integer.parseInt(value);
            default:
                return 0;
        }
    }