Write a Java program to convert a unix timestamp to date
This program converts a Unix timestamp (number of seconds elapsed since January 1, 1970, 00:00:00 UTC) to a human-readable date and time in a specific time zone. Here is a step-by-step explanation of the code:
- long unix_sec = 1372339860; - A Unix timestamp representing a specific moment in time (July 28, 2013, 01:57:40 UTC) is assigned to a variable unix_sec.
- Date date = new Date(unix_sec*1000L); - A Date object is created by multiplying the Unix timestamp by 1000L to convert it from seconds to milliseconds, and passing the resulting value to the Date constructor. This creates a Date object representing the same moment in time as the Unix timestamp.
- SimpleDateFormat d = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z"); - A SimpleDateFormat object is created with a specific pattern that defines the format of the output string. The pattern "yyyy-MM-dd HH:mm:ss z" specifies that the output string should contain the year, month, day, hour, minute, second, and time zone offset of the date and time.
- d.setTimeZone(TimeZone.getTimeZone("GMT-4")); - The time zone of the SimpleDateFormat object is set to a specific time zone ("GMT-4" in this case) using the setTimeZone method.
- String dt = d.format(date); - The format method of the SimpleDateFormat object is called with the Date object as a parameter to convert it to a string in the specified format.
- System.out.println(dt); - The resulting string is printed to the console. The output shows the date and time in the specified time zone: "2013-07-27 21:57:40 EDT" (Eastern Daylight Time, which is 4 hours behind UTC).
Source Code
import java.util.*;
import java.text.*;
public class Unix_Timestamp
{
public static void main(String[] args)
{
long unix_sec = 1372339860;
Date date = new Date(unix_sec*1000L);
SimpleDateFormat d = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
d.setTimeZone(TimeZone.getTimeZone("GMT-4"));
String dt = d.format(date);
System.out.println(dt);
}
}
Output
2013-06-27 09:31:00 GMT-04:00