Temporal Adjuster Example: Next Prime Hour

We are continuing with the temporal adjuster examples series. Lets see something different with this tutorial. In the previous examples, we saw date based temporal adjusters. In this Java tutorial, let us see a time based temporal adjuster.

Given a time, lets adjust it for the next prime hour. The hour where it is a prime number. To know about temporal adjusters, read this introduction to temporal adjuster tutorial.

package com.javapapers.java8.dateandtime;

import java.time.LocalTime;
import java.time.temporal.Temporal;
import java.time.temporal.TemporalAdjuster;

public class NextPrimeHourTemporalAdjuster implements TemporalAdjuster {

	public Temporal adjustInto(Temporal temporalAdjusterInput) {
		LocalTime temporalAdjusterTime = LocalTime.from(temporalAdjusterInput);
		int currentHour = temporalAdjusterTime.getHour();
		int primeHour = 1;
		if (currentHour < 23) {
			primeHour = getNextPrime(currentHour);
		LocalTime adjustedTime = LocalTime.of(primeHour, 0, 0);
		return adjustedTime;

	 * method to get the next prime number for the passed argument
	public int getNextPrime(int n) {
		int i, j, result = 0;

		for (j = n + 1; j < 24; j++) {
			for (i = 2; i < j; i++) {
				if (j % i == 0)
			if (i == j) {
				result = j;

		return result;

	public static void main(String... strings) {
		LocalTime currentTime = LocalTime.now();
		NextPrimeHourTemporalAdjuster primeHourAdjuster = new NextPrimeHourTemporalAdjuster();
		LocalTime nextPrimeHour = currentTime.with(primeHourAdjuster);
		System.out.println("Next Prime Hour: " + nextPrimeHour);


In this temporal adjuster program, we grab the hour from the temporal input time. Then we calculate the next prime number for that hour. Then construct a time object for this adjusted time and return it.

Temporal Adjuster Example Program Output

Next Prime Hour: 02:00

This Java tutorial was added on 14/08/2014.