How to Get Current Timestamp in Java
How can we obtain the current timestamp or date in Java?
If you want the current timestamp in milliseconds, check that out here!
1. Using System
or Date
We can get the current time using System.currentTimeMillis()
and convert to Timestamp
.
Timestamp ts = new Timestamp(System.currentTimeMillis());
We can also get the current time using new Date()
and convert to Timestamp
.
Date date = new Date();
Timestamp ts = new Timestamp(date.getTime());
2. Using Instant
Similarly, we can get the current time using Instant.now()
and convert to Timestamp
.
Timestamp ts = Timestamp.from(Instant.now())
We can also convert from Timestamp
to Instant
.
Instant instant = ts.toInstant();
3. Using ZonedDateTime
ZonedDateTime.now()
also gives us the current time. We can convert it to an Instant
, then to a Timestamp
.
Timestamp ts = Timestamp.from(ZonedDateTime.now().toInstant()));
4. Using LocalDateTime
With Java 8, we can get the current time using LocalDateTime.now()
and convert to Timestamp
.
Timestamp ts = Timestamp.valueOf(LocalDateTime.now())
Get milliseconds from Timestamp
or Instant
We can get the number of milliseconds since January 1, 1970, 00:00:00 GMT
from either Timestamp
or Instant
.
ts.getTime();
instant.toEpochMilli();