0

Can we pass a long value in Java such that it adds only seconds in the following code:

Calendar calendar= Calendar.getInstance();
calendar.add(Calendar.MINUTE, (int) **SomeLongValue**);

Where SomeLongValue adds only seconds to the calendar object.

I cannot change the code. I have to pass a long value and increase calendar only by seconds.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
Palak
  • 25
  • 1
  • 1
  • 8

2 Answers2

1

I think you want to achieve below:

Calendar calendar= Calendar.getInstance();
calendar.setTimeInMillis(calendar.getTimeInMillis() + (someLongValueInSec * 1000));
Maciej
  • 1,954
  • 10
  • 14
1

I'm going to say no, you cannot add only seconds. You're adding minutes, and an integer must be a whole number. Therefore, the least amount of seconds you can add given that code is 60 seconds.

I would suggest using Calendar.SECONDS if that's the time unit you actually want to use

I also would suggest using a LocalDateTime rather than a Calendar. It has a plusSeconds(long seconds) method

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • 1
    If using `ZonedDateTime` or `LocalDateTime` from java.time (certainly recommended) you could obtain great flexibility by using the `add(Duration)` method. That would allow the client to pass `Duration.ofMinutes(240)`, `Duration.ofSeconds(45)` and all thinkable combinations of different time units. PS In the code in the question you can add 0 seconds and even -60 seconds and less; not that it helps the OP. – Ole V.V. Mar 09 '18 at 08:53