fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. import java.time.* ;
  8. import java.time.format.* ;
  9. import java.time.temporal.* ;
  10. import java.time.chrono.* ;
  11.  
  12. /* Name of the class has to be "Main" only if the class is public. */
  13. class Ideone
  14. {
  15. public static void main (String[] args) throws java.lang.Exception
  16. {
  17. Ideone app = new Ideone() ;
  18. app.demo() ;
  19. }
  20.  
  21. private void demo ( )
  22. {
  23. final Instant start = Instant.now().minus( Duration.ofMinutes( 21 ) );
  24. final Integer price = 10; // This may come from some other place, such as a look-up in a database.
  25. Integer cost = this.calculateCostForElapsedTimeSoFar( start , price );
  26. System.out.println( "cost: " + cost );
  27. }
  28.  
  29. public Integer calculateCostForElapsedTimeSoFar ( final Instant start , final Integer price )
  30. {
  31. // Determine elapsed time.
  32. Instant now = Instant.now();
  33. Duration elapsed = Duration.between( start , now );
  34.  
  35. // See how many chunks of 15 minutes have occurred.
  36. Duration chunk = Duration.ofMinutes( 15 ); // Charge for every chunk of time in chunks of 15 minutes. You could make this a constant instead of a local variable.
  37. int chunks = Math.toIntExact( elapsed.dividedBy( chunk ) ); // Returns number of whole times a specified Duration occurs within this Duration.
  38.  
  39. // Calculate charges.
  40. Integer cost = ( price * chunks );
  41. return cost;
  42. }
  43. }
Success #stdin #stdout 0.13s 37000KB
stdin
Standard input is empty
stdout
cost: 10