3

How can I make an API for a class that the user passes a TimeUnit e.g. minutes, seconds, hours and a number and keep the millisec value internally in the class.
The following seems the only way?

void someMethodDays(int numOfDays) {  
   this.longValue = TimeUnit.DAYS.toMillis(numOfDays);  
}  

void someMethodHour(int numOfHours) {  
   this.longValue = TimeUnit.HOURS.toMillis(numOfDays);  
} etc  

Is this the only way? A method per value with a descriptive name for argument?

Jim
  • 3,845
  • 3
  • 22
  • 47

2 Answers2

3

You could model your class after a well-known and tested class: java.time.LocalDate, which provides the plus(long, TemporalUnit) method.

Similarly, you could create a someMethod(long, TimeUnit) method that allows callers to pass in arbitrary amounts of any TimeUnit.

void someMethod(long amount, TimeUnit unit) {
    this.longValue = unit.toMillis(amount);
}

Note that LocalDate also provides specialized methods for adding certain common units of time, like plusDays(). That gives the caller the ability to decide which is clearer for the code they're writing:

LocalDate tomorrow = today.plusDays(1);
LocalDate tomorrow = today.plus(1, TimeUnit.DAYS);
Ben P.
  • 52,661
  • 6
  • 95
  • 123
2

It seems to me that you don’t need to develop your own class; that you’ll be reinventing the wheel. I suggest you use the Duration class.

To convert from some time unit to a Duration:

    System.out.println(Duration.of(3, ChronoUnit.HOURS));

Or alternatively:

    System.out.println(Duration.ofHours(3));

Output is the same in both cases:

PT3H

It prints a little funny; this means a span of time of 3 hours. The format is ISO 8601.

    System.out.println(Duration.of(2, ChronoUnit.DAYS));

PT48H

48 hours; that’s correct.

    System.out.println(Duration.of(327864523, ChronoUnit.MICROS));

PT5M27.864523S

A span of 5 minutes 27.864523 seconds.

If you need to convert to milliseconds, the method is built in:

    Duration dur = Duration.of(284, ChronoUnit.MINUTES);
    System.out.println("" + dur.toMillis() + " milliseconds");

17040000 milliseconds

Duration is part of java.time, the modern Java date and time API, and of course works well with the other classes from that API.

Links

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Ole V.V.
  • 81,772
  • 15
  • 137
  • 161