It is common to represent timestamps in milliseconds in programming, but it’s often necessary to convert them into human-readable date and time formats for readability and presentation. Using the java.time
package we can convert a timestamp in milliseconds to a string-formatted time in Java.
Read timestamp:
First, we need a timestamp in milliseconds. We can get this from the external source, i.e., the backend API, or from the user. We can also generate this using the following API, i.e., System.currentTimeMillis()
.
For example, let us assume we have a timestamp in milliseconds.
long timestampMillis = 1632156962000L;
Note: Replace the above timestamp with your own timestamp
Converting the timestamp
To convert the timestamp to a string-formatted time, we can use the Instant
class from the java.time
package. Following is the example:
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
public class TimestampToStringExample {
public static void main(String[] args) {
long timestampMillis = 1632156962000L; // Replace with your timestamp
// Convert timestamp to Instant
Instant instant = Instant.ofEpochMilli(timestampMillis);
// Define the desired time zone
ZoneId zoneId = ZoneId.of("America/New_York");
// Format the Instant as a string
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
.withZone(zoneId);
String formattedTime = formatter.format(instant);
System.out.println("Formatted Time: " + formattedTime);
}
}
Explanation:
In the above example, we created an Instant
object using Instant.ofEpochMilli(timestampMillis)
, which represents a point in time.
We defined the desired time zone using ZoneId
. Please note, It’s important to specify the correct time zone to display the time in the intended region.
We format the Instant
as a string using DateTimeFormatter
. You can customize the format pattern as per your requirement.
In this example, we used “yyyy-MM-dd HH:mm:ss” to display the date and time in the format “YYYY-MM-DD HH:MM:SS.“
Customizing the Format
We can also customize the format pattern in the DateTimeFormatter
as per our requirements. Here are some common format symbols.
y
: YearM
: Monthd
: Day of the monthH
: Hour (0-23)m
: Minutes
: Second
For example, to display the date and time in a different format, such as “MM/DD/YYYY hh:mm a,” we can modify the pattern as shown below.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy hh:mm a")
.withZone(zoneId);