-2

I'm looking to code a function that would truncate a timestamp received to the nearest previous 15 minutes interval. I.e. 01:16:58 -> 01:15:00, 01:02:32 - >01:00:00, 01:30:00 ->01:30:00 etc.

Any idea of a nice simple way of coding it?

We're on Java 8

Thanks

Update: Pls note that the truncation is required, not the rounding. This is how the question is different from the other one that has been mentioned by a number or readers. So, this is NOT a duplicate.

spoonboy
  • 2,570
  • 5
  • 32
  • 56
  • what have you tried so far? a minute is an int, how would you round an int to the previous 15min? – Scary Wombat Feb 28 '18 at 01:09
  • How many seconds are 15 minutes? If you would know that - could it help? Do you know the modulo operator? Btw.: Finding the nearest, previous value isn't called rounding, it's called truncation. So 13:59:59 gets 13:45:00, right? – user unknown Feb 28 '18 at 01:10
  • Yes, you are right, the truncation is required, not rounding. This is how this question is different from the one mentioned earlier. – spoonboy Feb 28 '18 at 01:21
  • this is called rounding down... or flooring, in some other circles. There is literally nothing different with "truncating", one of the answers in the duplicate target addresses exactly this. – Félix Adriyel Gagnon-Grenier Feb 28 '18 at 22:57

1 Answers1

1
    Calendar cal = Calendar.getInstance();

    final int minutes = cal.get(Calendar.MINUTE);
    cal.set (Calendar.MINUTE, minutes - (minutes % 15));
    cal.set (Calendar.SECOND, 0);
    cal.set (Calendar.MILLISECOND, 0);

    System.out.println (new Date(cal.getTimeInMillis()));
Ari Singh
  • 1,228
  • 7
  • 12