Java time in and time out

Java LocalTime

Java LocalTime tutorial shows how to work with LocalTime in Java. We compute the current local time, parse local time, format local time, compare local time, and do time arithmetics.

Java LocalTime

is a time without a time-zone in the ISO-8601 calendar system. LocalTime is an immutable date-time object.

LocalTime does not store or represent a date or time-zone. It is a description of the local time as seen on a wall clock. , also called real-world time or wall-clock time, refers to elapsed time as determined by a chronometer such as a wristwatch or wall clock.

The equals method should be used for comparisons.

Java LocalTime current time

The current time is retrived with LocalTime.now .

package com.zetcode; import java.time.LocalTime; public class JavaLocalTimeNow < public static void main(String[] args) < LocalTime now = LocalTime.now(); System.out.println(now); >>

The example prints the local current time.

Java LocalTime create

The are several ways to create LocalTime in Java.

package com.zetcode; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.format.DateTimeFormatter; public class JavaLocalTimeCreate < public static void main(String[] args) < // Current Time LocalTime time1 = LocalTime.now(); System.out.println(time1); // Specific Time LocalTime time2 = LocalTime.of(7, 20, 45, 342123342); System.out.println(time2); // Specific Time LocalTime time3 = LocalTime.parse("12:32:22", DateTimeFormatter.ISO_TIME); System.out.println(time3); // Retrieving from LocalDateTime LocalTime time4 = LocalDateTime.now().toLocalTime(); System.out.println(time4); >>

The example presents four methods

LocalTime time1 = LocalTime.now();

The LocalTime.now creates a current local time.

LocalTime time2 = LocalTime.of(7, 20, 45, 342123342);

With LocalTime.of , we can create a specific local time from an hour, minute, second and nanosecond.

LocalTime time3 = LocalTime.parse("12:32:22", DateTimeFormatter.ISO_TIME);

With LocalTime.parse , we parse LocalTime from a string.

LocalTime time4 = LocalDateTime.now().toLocalTime();

It is also possible to get LocalTime from a LocalDateTime object.

18:18:12.135 07:20:45.342123342 12:32:22 18:18:12.186

Java LocalTime hour, minute, second

The following example splits a local time into hour, minute, and second parts.

package com.zetcode; import java.time.LocalTime; public class JavaLocalTimeParts < public static void main(String[] args) < LocalTime time = LocalTime.now(); System.out.printf("Hour: %s%n", time.getHour()); System.out.printf("Minute: %s%n", time.getMinute()); System.out.printf("Second: %s%n", time.getSecond()); >>

The getHour gets the hour part, the getMinute gets the minute part, and the getSecond the second part of the LocalTime .

Hour: 18 Minute: 25 Second: 55

Java LocalTime zones

We can compute a local time for a specific time zone. LocalTime , however, does not store time zone information.

package com.zetcode; import java.time.LocalTime; import java.time.ZoneId; import java.time.temporal.ChronoUnit; public class JavaLocalTimeZone < public static void main(String[] args) < ZoneId zone1 = ZoneId.of("Europe/Bratislava"); ZoneId zone2 = ZoneId.of("Europe/Moscow"); LocalTime now1 = LocalTime.now(zone1); LocalTime now2 = LocalTime.now(zone2); System.out.printf("Bratislava time: %s%n", now1); System.out.printf("Moscow time: %s%n", now2); long hoursBetween = ChronoUnit.HOURS.between(now1, now2); long minutesBetween = ChronoUnit.MINUTES.between(now1, now2); System.out.println(hoursBetween); System.out.println(minutesBetween); >>

The example finds out current local time for Moscow and Bratislava. We also compute the time difference between the two cities.

ZoneId zone1 = ZoneId.of("Europe/Bratislava"); ZoneId zone2 = ZoneId.of("Europe/Moscow");

We specify the time zones with ZoneId.of method.

LocalTime now1 = LocalTime.now(zone1); LocalTime now2 = LocalTime.now(zone2);

To create local times, we pass the zones to the LocalTime.now .

long hoursBetween = ChronoUnit.HOURS.between(now1, now2); long minutesBetween = ChronoUnit.MINUTES.between(now1, now2);

We compute the difference between the two cities in hours and minutes.

Bratislava time: 11:00:42.704 Moscow time: 13:00:42.732 2 120

Java LocalTime format

The time is formatted differently in various countries. DateTimeFormatter helps us format the time.

package com.zetcode; import java.time.LocalTime; import java.time.format.DateTimeFormatter; public class JavaLocalTimeFormat < public static void main(String[] args) < LocalTime now = LocalTime.now(); DateTimeFormatter dtf = DateTimeFormatter.ISO_TIME; System.out.println(now.format(dtf)); DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("hh:mm:ss"); System.out.println(now.format(dtf2)); DateTimeFormatter dtf3 = DateTimeFormatter.ofPattern("hh:mm:ss a"); System.out.println(now.format(dtf3)); >>

The example uses DateTimeFormatter to format time.

DateTimeFormatter dtf = DateTimeFormatter.ISO_TIME; System.out.println(now.format(dtf));

We format the time to the ISO format time standart.

DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("hh:mm:ss");

We can choose a specific time format with DateTimeFormatter.ofPattern . The documentation to DateTimeFormatter contains the description of various formatting characters that we can use.

11:08:56.483 11:08:56 11:08:56 AM

Java LocalTime arithmetic

Java LocalTime has methods for doing time arithmetics.

package com.zetcode; import java.time.LocalTime; public class JavaLocalTimeArithmetic < public static void main(String[] args) < LocalTime now = LocalTime.now(); System.out.println("Current Time: " + now); // LocalTime addition System.out.println("Adding 3 hours: " + now.plusHours(3)); System.out.println("Adding 30 minutes: " + now.plusMinutes(30)); System.out.println("Adding 45 seconds: " + now.plusSeconds(45)); System.out.println("Adding 40000 nanoseconds: " + now.plusNanos(40000)); // LocalTime subtraction System.out.println("Subtracting 3 hours: " + now.minusHours(3)); System.out.println("Subtracting 30 minutes: " + now.minusMinutes(30)); System.out.println("Subtracting 45 seconds: " + now.minusSeconds(45)); System.out.println("Subtracting 40000 nanoseconds: " + now.minusNanos(40000)); >>

The example presents method for adding and subtracting time units.

System.out.println("Adding 3 hours: " + localTime.plusHours(3));

The plusHours adds three hours to the current local time.

System.out.println("Subtracting 3 hours: " + now.minusHours(3));

Likewise, the minusHours subtracts three hours from the current local time.

Current Time: 11:12:51.155 Adding 3 hours: 14:12:51.155 Adding 30 minutes: 11:42:51.155 Adding 45 seconds: 11:13:36.155 Adding 40000 nanoseconds: 11:12:51.155040 Subtracting 3 hours: 08:12:51.155 Subtracting 30 minutes: 10:42:51.155 Subtracting 45 seconds: 11:12:06.155 Subtracting 40000 nanoseconds: 11:12:51.154960

Java LocalTime until

With the until method, we can compute the time until another time in terms of the specified unit.

package com.zetcode; import java.time.LocalTime; import java.time.temporal.ChronoUnit; public class JavaLocalTimeUntil < public static void main(String[] args) < LocalTime now = LocalTime.now(); LocalTime time = LocalTime.parse("22:15:30"); System.out.printf("%s hours%n", now.until(time, ChronoUnit.HOURS)); System.out.printf("%s minutes%n", now.until(time, ChronoUnit.MINUTES)); System.out.printf("%s seconds%n", now.until(time, ChronoUnit.SECONDS)); >>

The example calculates the time that has to elapse until another time in hours, minutes and seconds.

System.out.printf("%s hours%n", now.until(time, ChronoUnit.HOURS));

With ChronoUnit.HOURS , we specify that we calculate the the time difference in hours.

10 hours 657 minutes 39476 seconds

Java LocalTime compare

The following example shows how to compare times.

package com.zetcode; import java.time.LocalTime; public class JavaLocalTimeCompare < public static void main(String[] args) < LocalTime time1 = LocalTime.of(4, 23, 12); LocalTime time2 = LocalTime.of(8, 03, 50); LocalTime time3 = LocalTime.of(12, 47, 35); if (time1.compareTo(time2) == 0) < System.out.println("time1 and time2 are equal"); >else < System.out.println("time1 and time2 are not equal"); >if (time2.isBefore(time3)) < System.out.println("time2 comes before time3"); >else < System.out.println("time2 does not come before time3"); >if (time3.isAfter(time1)) < System.out.println("time3 comes after time1"); >else < System.out.println("time3 does not come after time1"); >> >

The example compares times. We check if they are equal, if the come before or after another time.

if (time1.compareTo(time2) == 0) 

The compareTo compares two local times.

The isBefore checks if a time comes before another time.

The isAfter checks if a time comes after another time.

time1 and time2 are not equal time2 comes before time3 time3 comes after time1

Java LocalTime truncate

The LocalTime's truncatedTo method returns a copy of a local time with the time truncated.

package com.zetcode; import java.time.LocalTime; import java.time.temporal.ChronoUnit; public class JavaLocaTimeTruncate < public static void main(String[] args) < LocalTime now = LocalTime.now(); System.out.println(now); System.out.println(now.truncatedTo(ChronoUnit.HALF_DAYS)); System.out.println(now.truncatedTo(ChronoUnit.HOURS)); System.out.println(now.truncatedTo(ChronoUnit.MINUTES)); System.out.println(now.truncatedTo(ChronoUnit.SECONDS)); System.out.println(now.truncatedTo(ChronoUnit.MICROS)); >>

The example uses truncatedTo to truncate time to half days, hours, minutes, seconds, and micros.

11:27:56.309 00:00 11:00 11:27 11:27:56 11:27:56.309

In this article we have worked with Java LocalTime.

Author

My name is Jan Bodnar and I am a passionate programmer with many years of programming experience. I have been writing programming articles since 2007. So far, I have written over 1400 articles and 8 e-books. I have over eight years of experience in teaching programming.

Источник

Java TimerTask to perform hard timeout on HTTP Calls

Java TimerTask provides a way to schedule a task using the standard Java Timer class. This is quite handy when we want to run a task at regular time intervals. Another practical application of this feature is to perform a hard timeout on HTTP calls when the user experience is suffering due to long running HTTP calls.

We will be seeing both the use-cases in this post with code examples.

1 – Introduction to Java TimerTask

Java TimerTask is an in-built class that implements the Runnable interface. We need to extend this class to create our own TimerTask that can be scheduled using the Java Timer class.

Java Timer class is thread-safe in nature. In other words, multiple threads can share a single Timer object without any need for external synchronization.

See below example code to understand Java TimerTask.

import java.util.Date; import java.util.Timer; import java.util.TimerTask; public class TimeTaskDemo extends TimerTask < @Override public void run < System.out.println("Starting Timer Task at:" + new Date()); executeTask(); System.out.println("Finishing Timer Task at:" + new Date()); > private void executeTask < try < //assuming it takes 5 secs to complete the task Thread.sleep(5000); > catch (InterruptedException e) < e.printStackTrace(); >> public static void main < TimerTask timerTask = new TimeTaskDemo(); Timer timer = new Timer(true); timer.scheduleAtFixedRate(timerTask, 0, 10*1000); System.out.println("Timer Task Started"); try < Thread.sleep(15000); > catch (InterruptedException e) < e.printStackTrace(); >timer.cancel(); System.out.println("Timer Task Cancelled"); try < Thread.sleep(30000); > catch (InterruptedException e) < e.printStackTrace(); >> >

Let us try to understand what is going on here:

  • The TimerTaskDemo class extends the abstract TimerTask class and overrides the run() method.
  • In the run() method, we simply simulate a task execution by making the thread sleep for 5 seconds.
  • Now, in the main() method, we instantiate the TimerTaskDemo class and also the Timer class. The Timer class constructor takes the flag isDaemon as input. We set it to true.
  • Then, we schedule the timerTask using scheduleAtFixedRate() method provided by the Timer class.
  • The scheduleAtFixedRate() method takes 3 arguments – the TimerTask instance, delay in task execution and interval between successive tasks. Here, delay is 0 seconds and interval is 10 seconds.
  • Lastly, we let the thread sleep for 15 seconds to allow the tasks to be executed. Finally, we cancel the timer using the cancel() method.

If we run the above program, below is the output we will get:

Timer Task Started Starting Timer Task at:Sat Jul 03 09:13:02 IST 2021 Finishing Timer Task at:Sat Jul 03 09:13:07 IST 2021 Starting Timer Task at:Sat Jul 03 09:13:12 IST 2021 Timer Task Cancelled Finishing Timer Task at:Sat Jul 03 09:13:17 IST 2021 Process finished with exit code 0

Some important points:

  • If a task is already running, the Timer will wait for it to finish before starting the next task from the queue.
  • We can execute tasks as daemon threads. Daemon threads are basically low priority threads that perform background operations.
  • Cancel method terminates the timer and discards any scheduled tasks. However, running tasks will still finish.
  • If we run the timer as daemon thread, it will terminate as soon as all threads finish execution.

2 – Java TimerTask for HTTP Calls

Now that we have understood the basics of Java TimerTask, we can move to the main objective of this post. The objective is to use Java TimerTask to perform hard timeout for HTTP Calls.

If you are not aware about Java HTTPClient timeout properties, you can go through this post where we talk in detail about the various timeout properties. On a basic level, there are various type of timeouts such as socket timeout, connection timeout. We can set all these properties individually.

However, many times we also need to have an overall hard timeout on the request level. For example, during the download of a potentially large file, the connection may be established but we need to ensure that the operation doesn’t go over a certain threshold. The Java HTTPClient does not have any configuration that can help us achieve such a hard timeout. However, it does provide an abort functionality that we can use along with the TimerTask to achieve hard timeout.

Below is the example code for the same.

HttpGet getMethod = new HttpGet( "http://localhost:8080/api/employees/1"); int hardTimeout = 5; // seconds TimerTask task = new TimerTask() < @Override public void run() < if (getMethod != null) < getMethod.abort(); >> >; new Timer(true).schedule(task, hardTimeout * 1000); HttpResponse response = httpClient.execute(getMethod); System.out.println( "HTTP Status of response: " + response.getStatusLine().getStatusCode());

As you can see here, we create a HttpGet object. Next, we create a TimerTask and override its run() method to abort the HTTP call whenever required. Now, we can schedule the task to run after 1 second. Basically, we imply that after 1 second, the abort() method will be called and the HTTP call will terminate. Lastly, we execute the getMethod using httpClient.

With this, we complete our demonstration of Java TimerTask and how we can use it to achieve hard timeout for HTTP requests using the abort() method.

Источник

Читайте также:  Html padding top right bottom left
Оцените статью