Java 17 Recipes
-12. Obtaining a Machine Timestamp
Download 3.2 Mb. Pdf ko'rish
|
Java 17 Recipes
- Bu sahifa navigatsiya:
- How It Works
4-12. Obtaining a Machine Timestamp
Problem You need to obtain a machine-based timestamp from the system. Chapter 4 Numbers aNd dates 132 Solution Utilize an Instant class, which represents the start of a nanosecond on the timeline based on machine time. In the following example, an Instant class obtains the system timestamp. The Instant class is also utilized in other scenarios, such as when calculating different dates based on the Instant. public static void instants(){ Instant timestamp = Instant.now(); System.out.println("The current timestamp: " + timestamp); //Now minus three days Instant minusThree = timestamp.minus(3, ChronoUnit.DAYS); System.out.println("Now minus three days:" + minusThree); ZonedDateTime atZone = timestamp.atZone(ZoneId.of("GMT")); System.out.println(atZone); Instant yesterday = Instant.now().minus(24, ChronoUnit.HOURS); System.out.println("Yesterday: " + yesterday); } Here is the result. The current timestamp: 2021-10-13T21:06:50.203477900Z Now minus three days:2021-10-10T21:06:50.203477900Z 2021-10-13T21:06:50.203477900Z[GMT] Yesterday: 2021-10-12T21:06:50.221430600Z How It Works The Date-Time API introduces a new class named Instant, which represents the start of a nanosecond on the timeline in machine-based time. Based on machine time, the value in an Instant class counts from EPOCH (January 1, 1970 00:00:00Z). Any values prior to the EPOCH are negative, and after the EPOCH the values are positive. The Instant class is perfect for obtaining a machine timestamp, as it includes all pertinent date and time information to the nanosecond. Chapter 4 Numbers aNd dates 133 An Instant class is static and immutable, so the now() method can be called to obtain the current timestamp. Doing so returns a copy of the current Instant. The Instant class also includes conversion and calculation methods. Each returns copies of the Instant class or other types. In the solution, the now() method returns the current timestamp, and then a couple of examples follow, showing how to perform calculations and obtain information on the Instant. The Instant class is an important new feature in Java 8 because it makes it easy to work with the current time and date data. The other date and time classes, such as LocalDateTime, are also useful. However, the Instant class is the most accurate timestamp because it’s based on nanosecond accuracy. Download 3.2 Mb. Do'stlaringiz bilan baham: |
Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling
ma'muriyatiga murojaat qiling