Timestamp Basics in Java
Java provides several classes to handle date and time, including java.util.Date
, java.time.Instant
, java.time.LocalDateTime
, and java.time.ZonedDateTime
. Among these, java.time.Instant
is commonly used to represent a timestamp, which is a point in time that can be measured in seconds and nanoseconds since the Unix epoch (January 1, 1970, 00:00:00 UTC).
To create an Instant
object, you can use the Instant.now()
method to get the current timestamp, or the Instant.ofEpochSecond()
method to create an Instant
from a specific number of seconds since the Unix epoch.
// Get the current timestamp
Instant currentTimestamp = Instant.now();
// Create a timestamp from a specific number of seconds
Instant customTimestamp = Instant.ofEpochSecond(1648777200); // April 1, 2022, 00:00:00 UTC
The Instant
class also provides various methods to manipulate and format timestamps, such as Instant.plus()
, Instant.minus()
, and Instant.toString()
.
// Add 1 hour to the current timestamp
Instant oneHourLater = currentTimestamp.plus(Duration.ofHours(1));
// Convert the timestamp to a string
String timestampString = currentTimestamp.toString(); // "2023-04-12T12:34:56.789Z"
By understanding the basics of timestamps in Java, you can effectively handle date and time-related tasks in your applications.